before(:each) for all tests except one
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.
Putting this kind of code into spec helper seems a bit odd. Feature specs is all you have? No unit tests? Even if it's the former, copy that code into individual specs that need it. If they're all in the same file, you can use contexts to prevent some duplication.
RSpec.describe 'something' do
context 'specs with login' do
before do
login(email, password)
visit root_url
end
it { ... }
end
context 'specs without login' do
it { ... }
end
end
Global rspec config in spec_helper.rb is meant for other things. Ones that make sense for each and every spec. Like, for example, cleaning a database.
config.before :each do
DatabaseCleaner.clean
end