_yrafw
Last Updated: September 21, 2016
·
10.67K
· ck3g
809ac34c7d3f932baf08bba11c486b9a

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) or before(: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
Say Thanks
Respond

4 Responses
Add your response

15511
Faff411a9ca427b444717ca9044a8e4f

Excelent, thanks

over 1 year ago ·
16073
A49760a3cd2023264e71e265d007ae17

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 :)

over 1 year ago ·
16075
809ac34c7d3f932baf08bba11c486b9a

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.

over 1 year ago ·
28135

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

over 1 year ago ·