I was complaining a few days ago that I was having trouble with authentication in cucumber stories in conjunction with RSpec. It turned out I was making a very stupid mistake (”administrator” and “admin” are not, in fact, the same thing). But in the interests of helping out anyone who ends up here via search engine, here’s how I’ve got it sorted out for now.

Here’s one of our current cucumber scenarios:


  Scenario: See all vendors
	Given I am logged in as a user in the administrator role
	And There are 3 vendors
	When I go to the manage vendors page
	Then I should see the first 3 vendor names

And here’s the corresponding part of the step file that handles the login:


Given /i am logged in as a user in the (.*) role/i do |role|
  @user = Factory.create(:user, :name => "the user",
    :login => "the_login",
    :password => "password",
    :password_confirmation => "password")
  @role = Factory.create(:role, :rolename => role)
  @user.roles << @role
  visits "/login"
  fills_in("login", :with => "the_login")
  fills_in("password", :with => "password")
  clicks_button("Log in")
end

Note that I’m using Factory Girl to instantiate objects in this application’s tests.

There may be a better pattern for this - I’m just getting started with cucumber. But for now, it works for me.