Nathan Long
Nathan Long

Reputation: 125902

How can I skip some setup for specific Rspec tags?

Rspec makes it easy to configure setup based on the presence of test tags. For example, if some tests need a parallel universe to be created (assuming you have code to do that):

# some_spec.rb
describe "in a parallel universe", alter_spacetime: true do
  # whatever
end

# spec_helper.rb
RSpec.configure do |config|
  config.before(:each, :alter_spacetime) do |example|
    # fancy magic here
  end
end

But I want to do the opposite: "before each test, unless you see this tag, do the following..."

How can I skip a setup step in spec_helper based on the presence of a tag on some tests?

Upvotes: 6

Views: 1174

Answers (1)

Ivan Kolmychek
Ivan Kolmychek

Reputation: 1271

At first, you would expect something like

RSpec.configure do |config|
  config.before(:each, alter_spacetime: false) do |example|
    # fancy magic here
  end
end

to work that way, but it doesn't.

But you have access to example, which is an Example instance and has the #metadata method, which returns Metadata object. You can check the value of the flag with that, and a flag on the specific example will override one on the containing describe block.

config.before(:each) do |example|
  # Note that we're not using a block param to get `example`
  unless example.metadata[:alter_spacetime] == false
    # fancy magic here
  end
end

Upvotes: 8

Related Questions