Lucas Benicio
Lucas Benicio

Reputation: 1

How to run all examples except one in Ruby using Rspec

config.before(:example,) do
    visit '/'
   find('a[class=btn').click
   fill_in 'username', with: $email
   fill_in 'password', with: $password
   find('input[class=btn]').click
end

I want to log in to the website in all tests except one, how do i do that?

I tried this:

config.before(:example,) |test| do
    visit '/'
   find('a[class=btn').click
   fill_in 'username', with: $email
   fill_in 'password', with: $password
   find('input[class=btn]').click 
   unless test.metadata[:notrun]
   end
end

I was expecting all test run except the one with the tag :notrun, but it runs anyway

Upvotes: 0

Views: 101

Answers (2)

aridlehoover
aridlehoover

Reputation: 3585

If I understand correctly, the OP wants to login before every test except one. Using skip: true will actually skip the test, not the before block.

There is a way to configure a before block to only execute on certain tests using metadata. It works like this:

RSpec.configure do |config|
  config.before(:each, login: true) do
    visit '/'
    find('a[class=btn').click
    fill_in 'username', with: $email
    fill_in 'password', with: $password
    find('input[class=btn]').click 
  end
end

RSpec.describe 'MyController' do
  describe '#index' do 
    it 'does something while logged out'

    context 'logged in', login: true do
      it 'does something while logged in'
      it 'does something else while logged in'
    end
  end
end

You can place the metadata on any describe, context, or example/it block. So, if you had a file full of tests that should be logged in, you'd just put the metadata on the outermost describe at the top of the file.

Upvotes: 0

Thomas Walpole
Thomas Walpole

Reputation: 49890

Your unless block is just

unless test.metadata[:notrun] end

so it's not doing anything. If you wanted the code in the before to not run then you could wrap it all in the unless

config.before(:example) |test| do
  unless test.metadata[:notrun]
    visit '/'
    find('a[class=btn').click
    fill_in 'username', with: $email
    fill_in 'password', with: $password
    find('input[class=btn]').click 
  end
end

but that will just stop the before hook from doing anything on the tagged test(s), it won't actually prevent the test from being run. Easiest way to prevent a specific example from being run is just to tag it with skip (instead of your notrun)

it 'blah blah', skip: true do
  ....
end

Upvotes: 2

Related Questions