There are several ways to run a single spec. I usually copy the spec file path with the line number of the example and pass it to the RSpec binary: bin/rspec spec/models/user_spec.rb:30
(multiple line numbers work as well: :30:36:68
). Another is to tag the example with focus: true
or to run the example by matching its name.
In this card I'd like to promote the "example id" or "nesting index" syntax. Its advantage is that it does not rely on line numbers.
- Handy when working on multiple examples, one by one. Just increase the last index when proceeding to the next example.
- Handy when the test file frequently changes, e.g. because
before
blocks are modified. The line number approach would easily loose track of the desired example.
Nesting index syntax looks like this: spec/models/user_spec.rb[1:2:1]
. It describes a path in the nesting tree of the spec file, with 1-based indexes.
Example
# spec/models/user_spec.rb
describe User do
it 'validates presence of its email address'
describe '#full_name' do
it 'combines first and last name'
it 'does not crash if first name is missing'
end
context 'when admin' do
before { … }
describe '#last_action' do
it 'returns the last action performed by the user'
it 'is nil for a new user'
end
end
end
The first example is run with
bin/rspec spec/models/user_spec.rb[1:1]
[1:1]
means: within the 1st block (namely describe User
), run the 1st example.
The last example is run with
bin/rspec spec/models/user_spec.rb[1:3:1:2]
[1:3:1:2]
means: within the 1st block (namely describe User
), find the 3rd block (namely context
), then find the 1st block within (namely describe '#last_action'
), then run the 2nd example within (it 'is nil for a new user'
).