Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

before(:each) for all tests except one

Tags:

This is part of my spec_helper.rb:

RSpec.configure do |config|

 config.before(:each) do
  login(email, password)
  visit root_url
 end

end

that I need in all of my (20+) tests except one.

Is there a way to avoid that single test to execute the before hook?

like image 661
thefabbulus Avatar asked Dec 22 '15 14:12

thefabbulus


1 Answers

You can add metadata to tests that do not need to login, then evaluate that metadata in your before hook.

For example, two tests in the same file. One needs to login and one does not.

# foo_spec.rb
describe Foo do
  describe "#bar" do
    it "needs to log in" do
      expect(1).to eq 1
    end
  end
  describe "#baz" do
    it "needs to not log in", :logged_out do
      expect(1).to eq 1
    end
  end
end

So we added metadata to our it block. Next, we configure the before hook to evaluate the example's metadata.

config.before(:each) do |test|
  login(email, password) unless test.metadata[:logged_out]
  visit root_url
end

Now, each test will visit root_url but only the ones not tagged with :logged_out will call login.

RSpec calls these metadata based hooks filters. You can learn a bit more about them here.

like image 174
Johnson Avatar answered Sep 16 '22 18:09

Johnson