Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I skip some setup for specific Rspec tags?

Tags:

ruby

rspec

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?

like image 457
Nathan Long Avatar asked Jan 09 '15 15:01

Nathan Long


1 Answers

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
like image 179
Ivan Kolmychek Avatar answered Oct 24 '22 11:10

Ivan Kolmychek