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
matches.
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
Show archive.org 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.