A Fresh Cup is Mike Gunderloy's software development weblog, covering Ruby on Rails and whatever else I find interesting in the universe of software. I'm a full-time Rails developer and contributor, available for long- or short-term consulting, with solid experience in working as part of a distributed team. If you'd like to hire me, drop me a line. I'm also the author of Rails Rescue Handbook and Rails Freelancing Handbook.

Navigation
« Double Shot #310 | Main | Double Shot #309 »
Thursday
09Oct2008

Authentication in Cucumber Tests

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:

[sourcecode language='ruby']
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
[/sourcecode]

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

[sourcecode language='ruby']
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
[/sourcecode]

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.

Reader Comments (2)

Great post. I currently have factories setup w/ cucumber like this:

(env.rb)
require 'factory_girl'

Before do
require File.join(RAILS_ROOT, 'test', 'factories')
end

Then in your (setups.rb) you can create your object using one line.

Given /I am logged in as a user/ do
@user = Factory(:user)
end

April 13, 2009 | Unregistered Commenternick treadway

s

December 30, 2009 | Unregistered Commenterc

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>