Posted almost 3 years ago. Visible to the public. Linked content.

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

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' end # something_shared.rb shared_examples_for 'something shared' do it 'does something' end

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:
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.

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Dominik Schöler
Last edit:
7 months ago
by Thomas Eisenbarth
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Dominik Schöler to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more