Mar 31, 2009

Testing Rails Authlogic with Cucumber

In early rails projects I rolled my own authentication system, later I used restful-authentication. This time I'm going to try out AuthLogic which seems to be fairly popular, cleanly packaged and actively developed. I may walk through an AuthLogic installation in a future post but today I just want to make sure it can play nicely with cucumber.

First I wrote a fairly basic login scenario. You'll notice I stuck with the declarative style in writing this and I followed the advice provided in "The RSpec Book". I use direct model access to create the registered user in the 'Given' but then use simulated browser access to do the login and verify the actions success.

Scenario: successful login
Given I am the registered user John Doe
And I am on the login page
When I login with valid credentials
Then I should be on the account page
And I should see "Login successful!"


This left me with three steps to implement:

Given /^I am the registered user (.+)$/ do |login|
params = {
"login"=> login,
"password"=>"password",
"password_confirmation"=>"password"
}
@user = User.create(params)
end

When /^I login with valid credentials$/ do
fill_in('Login', :with => @user.login)
fill_in('Password', :with => "password")
click_button("Login")
end

Then /^I should be on ([^\"]*)$/ do |page_name|
response.request.path.should == path_to(page_name)
end

All fairly straight forward. I don't expect any problems using Cucumber with Authlogic.

4 comments:

Jesse said...

this really helps me out.. however, why aren't the other steps listed? i had to make a "visit path_to /the login page/" step. ?

bantic said...

The visit* steps come from webrat, you'll want to install the webrat steps along w/ cucumber. I believe the cucumber generator creates these.

Anonymous said...

Well, considering how many people (including me) who are having problems integrating authlogic with cucumber testing, I'm curious to hear whether your expectations were correct..?

Jordan said...

This attempt is almost correct (at least in the current version of authlogic, v2.1). Instead of calling User.create you'll want to call User.new and then save it using @user.save_without_session_maintenance.

Otherwise authlogic will blow up trying to look for non-existent http request data in a non-existent controller. However nice authlogic may be, it blows Rails's MVC separation all to hell.