RSpec: Tagging examples and example groups

Updated . Posted . Visible to the public. Repeats.

In RSpec you can tag examples or example groups with any tags you like simply by saying

describe ReportCreator, slow: true do
  # ..
end

describe ReportCreator do
  it 'generates reports', slow: true do
    # ...
  end
end

You can then only run examples with these tags.

rspec --tag slow
rspec -t slow

# Using the parallel_tests gem
rake "parallel:spec[,,--tag slow]"

Or you can run all examples except the ones with a certain tag:

rspec --tag ~slow # note the ~
rspec -t ~slow

# Using the parallel_tests gem
rake "parallel:spec[,,--tag ~slow]"

You can also assign values to tags, and only run or exclude those tags where the values match a given string.

describe ReportCreator do
  it 'generates reports', speed: 'slow' do
    # ...
  end
end

rspec . --tag speed:slow # Only run examples tagged with speed: 'slow'
rspec . --tag ~speed:slow # Run examples except the ones tagged with speed: 'slow'

You can use the tags for hooks and includes, too.

RSpec.configure do |config|
  config.before(:each, slow: true) do
    # Do one thing here
  end
end
RSpec.configure do |config|
  config.include SlowHelpers, type: :slow
end

Note that RSpec will, although it prints your tags inclusion/exclusion config before the suite run, ignore tag config when you pass it a spec file with a line number. That's even when the line number references a describe or context block, where only some examples should be excluded.

Thomas Klemm
Last edit
Emanuel
License
Source code in this card is licensed under the MIT License.
Posted by Thomas Klemm to makandra dev (2015-04-20 14:39)