OLM On Rails

Testing Rails with Authentication

leave a comment »

I’ve been putting off doing functional testing with rails for a while now because of the snag that we couldn’t figure out how to test with authentication.  Finally I’ve decided to solve this once and for all and get to the root of the problem. First approach we tried was to explicitly log in using a post request to the login page in the test setup. Of course, it didn’t work as each request I believe is independent of the subsequent requests, at least during functional testing.

The next approach we tried was to go down one level and expose the method that sets the current user for the session, and then call that as a controller function.  This made me a bit uneasy because we were making the current user setter public, which could probably mean that it would be exposed as an action that can be exploited.  Either way, this approach still didn’t work and was still giving us a 302 redirected status.

We decided to go one more level down and tried then to explicitly set the session hash, which is how we keep track of the current user.  One way that I came across was to set the session variable in a request object, that is

def setup
@controller = AssignmentsController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
@admin = users(:admin)
@request.session['uid'] = @admin.id # login before testing
end

or some reason, this didn’t work out either.  Finally, it turns out that session variables can be set on every (get/post/put/delete) request made as an optional parameter. Now, each of the request type methods are wrapped with an extra user parameter to make that request on behalf of that user. For example, we now have a get_as method defined as:

# Performs GET request as the supplied user for authentication
def get_as(user, action, params=nil, flash=nil)
session_vars = { 'uid' => user.id, 'timeout' => 3.days.from_now }
get(action, params, session_vars, flash)
end

Advertisements

Written by Geofrey

November 7, 2008 at 2:38 pm

Posted in OLM on Rails

Tagged with , ,

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

%d bloggers like this: