RSpec : Conditionals in before/after callbacks

Conditions

When you add a conditions hash to before(:example) or before(:context), RSpec will only apply that hook to groups or examples that match the conditions. e.g.

RSpec.configure do |config|
  config.before(:example, :authorized => true) do
     :authorized_user
  end
end

describe Something, :authorized => true do
  # The before hook will run in before each example in this group.
end

describe SomethingElse do
  it "does something", :authorized => true do
    # The before hook will run before this example.
  end

  it "does something else" do
    # The hook will not run before this example.
  end
end

 

Or

config.before(:each) do |ex|
  if ex.metadata[:admin] == true
    Rails.application.load_seed # loading seeds
  end
end

it "should auto fill the shipping date field to today's date", :admin => true  do
  expect(User.find_by_email('user@example.com')).not_to eq(nil)
end

Sources

http://www.rubydoc.info/github/rspec/rspec-core/RSpec/Core/Hooks#before-instance_method

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s