Changing How Your Specs Run

RSpec allows you to change the way your specs behave using metadata. You’ve already used this ability several times as you’ve worked through this book. Here are the metadata options that affect how RSpec runs your examples:

:aggregate_failures

Changes how RSpec reacts to failure so that each example runs to completion (instead of stopping at the first failed expectation)

:pending

Indicates that you expect the example to fail; RSpec will run it and report it as pending if it did fail, or report it as a failure if it passed

:skip

Tells RSpec to skip the example entirely but still list the example in the output (unlike with filtering, which omits the example from the output)

:order

Sets the order in which RSpec runs your specs (can be the same order as they’re defined, random order, or a custom order)

Both :pending and :skip take an optional explanation for why this spec shouldn’t be run normally, which RSpec will print in the output.

As we discussed in Testing the Invalid Case, RSpec is capable of running your specs in :random order, and we generally recommend you do that. The main alternative is :defined, meaning that RSpec runs your examples in the order that it sees their definitions.

The choice between :defined and :random doesn’t need to be either/or. If you’re migrating an entire RSpec suite from the former to the latter, it can be difficult to make the switch all at once. As you saw in the expense tracker exercise, examples can have hidden order dependencies.

You can use metadata to make the transition to random ordering more gradual. By tagging an example group with order: :random, you can run just the examples in that group randomly:

 RSpec.describe SomeNewExampleGroup, ​order: :random​ ​do
 # ...
 end

Once you’ve transitioned all your groups to random ordering, you can remove this metadata and then turn on randomness for the entire suite in your RSpec.configure block.

On rare occasions, you’ll need even more fine-grained control over spec ordering. For example, you may want to run all your unit specs first, or run all your specs in order from fastest to slowest. In these cases, you can set the :order metadata to a custom ordering. The RSpec docs explain how to do so.[59]

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset