Skipping `before` hook for a few test cases in Rspec
As you probably know you're able to pass condition
into before
method.
When you add a conditions hash to
before(:each)
orbefore(:all)
, RSpec will only apply that hook to groups or examples that match the conditions. e.g.
From Rspec doc
But sometimes it's necessary to skip a few test cases out of a mass. It's annoying to add tag to each example.
You're able to use conditional statements to check example.metadata
:
before do
unless example.metadata[:skip_before]
# before body
end
end
it "does something" do
# before hook will run before this example
end
it "does something else", skip_before: true do
# before hook will be skipped
end
Written by Vitaly
Related protips
4 Responses
Excelent, thanks
I'm new to Rspec but either this method does not work anymore or it contains an error.
Anyways with Ruby >= 2.0 and Rspec >= 3.0 you have to give the bloc a parameter:
before do |example|
unless example.metadata[:skip_before]
# before body
end
end
it "does something" do
# before hook will run before this example
end
it "does something else", :skip_before do
# before hook will be skipped
end
and you also do not need skip_before: true
, you can just use :skip_before
But thanks for the hint :)
Yeah. I've wrote that tip during the reign of RSpec 2 In RSpec 3 you should pass parameter into block like you've described.
Thanks for share this. However, I found that example is undefined. My rspec version is 3. I came up with solution like this:
RSpec.current_example.metadata[:skipbefore]
Thanks Again