Thursday, November 5, 2009

Authlogic and Functional Tests

After adding Authlogic to my Rails application, functional tests failed with errors like
Expected response to be a <:success>, but was <302>
This is because the controllers now require a valid session. Here are the steps to easliy accomplish this:

1. Create a named user in fixtures/users.yml, as described in docs. I called my user auto
auto:
username: autotester
email: whatever@whatever.com
password_salt: <%= salt = Authlogic::Random.hex_token %>
crypted_password: <%= Authlogic::CryptoProviders::Sha512.encrypt("autouserpw" + salt) %>
persistence_token: <%= Authlogic::Random.hex_token %>


2. Activate AuthLogic at setup time of test
setup :activate_authlogic
within each ControllerTest class (ActionController::TestCase)

3. Add helper to create a session in test_helper.rb
class ActionController::TestCase
def within_session(user = :auto)
authlogic_session = UserSession.create(users(user))
yield if block_given?
authlogic_session.destroy
end
end


4. Put a within_session block around the areas of a test which need it. Change tests like this:
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:releases)
end

To tests like this:
test "should get index" do
within_session do
get :index
assert_response :success
assert_not_nil assigns(:releases)
end
end

And that's it.

1 comment:

Anonymous said...

The information here is great. I will invite my friends here.

Thanks