Running Rspec examples by name, or: Running a single shared example

Updated . Posted . Visible to the public.

When an Rspec example fails, I usually investigate by running that example again using rspec <file:line>. However, this does not work with shared examples, since Rspec doesn't know in which context the shared example should be run.

But there is a different way: You can run the shared example using the -e, --example option. It takes a string value and runs all scenarios containing that substring in their full description.

This allows you to run a single uniquely named example, all examples with
similar names, all the examples in a uniquely named group, etc, etc.

You can also use the option more than once to specify multiple example


Let the following setup:

# my_model_spec.rb
describe MyModel do
  it 'perfoms a test'
  it_behaves_like 'something shared'

# something_shared.rb
shared_examples_for 'something shared' do
  it 'does something'

When the shared example "it does something" fails, you can run it like this:

rspec spec/models/my_model_spec.rb --example 'something'

If you are using Rspec >= 3.3 you could also run a shared example by it's ID.

The ID of an Example/-Group is the combination of the filename and the nested index (starting from 1) in brackets. To run the shared example from above you could execute:

rspec spec/models/my_model_spec.rb[1:2:1]

Note that if an example from a shared example group fails, RSpec will print out the file name with that ID. You just need to paste it to your console.

Further Explanation regarding the IDs of Example/-Groups Show snapshot :
The ID of the ExampleGroup created by describe MyModel is spec/models/my_model_spec.rb[1].
The ID of the ExampleGroup created by it 'performs a test' is spec/models/my_model_spec.rb[1:1].
The ID of the ExampleGroup created by it_behaves_like 'something shared' is spec/models/my_model_spec.rb[1:2] as it is the second ExampleGroup in the MyModel-ExampleGroup.
Then rpsec spec/models/my_model_spec.rb[1:2:1] is the first example (it 'does something') of this group.

Dominik Schöler
Last edit
Henning Koch
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2017-09-21 10:15)