Passing Sessions and Referers in Rails Functional Tests

So, you’ve set up your Rails app to present different views to authenticated people verses non. Now, how do you test functionality for the authenticated people?

Seems silly to have your tests sign in before checking whatever it is you want them to check.

Well, pass the session data in the test as a hash. Turns out the action tests are formatted like this:
method :action, {action variables hash}, {session variables hash}
Pretty straight-forward, except the session variables need to be passed as ‘strings’, not :symbols.
This works:
post :add_member, {:email => 'test@test.com', :group => '1'}, {'person_id' => '1'}

This doesn’t
post :add_member, {:email => 'test@test.com', :group => '1'}, {:person_id => '1'}

A less than intuitive distinction that I’ve bumped into before with cookies

Also a big thanks to Jon @ Ruby Nuggets for the tip passing referers info in the tests:
@request.env['HTTP_REFERER'] = 'http://foo'
not the @request.referer = ‘http://foo’ that I assumed.

4 thoughts on “Passing Sessions and Referers in Rails Functional Tests

  1. thank you garrick, you saved me some time!
    the question remains why you should use a symbol, when you are not able to test your application.

  2. This is a very helpful tip, thanks! Suddenly my last roadblock to proper functional testing (and excuse for not doing it) is gone.

    For me though, it seems to work the opposite: It only works if I pass in symbols as keys, NOT if I pass in strings. Maybe that’s because in my session-checking routines I’m always accessing my session values with symbol-keys, and maybe you’re using strings?

Comments are closed.