When doing functional test, sooner or later you will need to do some testing with cookie, for example when you need to test the infamous ‘Remember me’ functionality.

It is easy to do that in Rails with some points to take note:

To set a cookie in a request:

@request.cookies['name'] = CGI::Cookie.new('name', 'cookie value')

To retrieve a cookie after a response:

cookies['name']
Note: Use a string for cookie name, symbol somehow returns nil in functional test.

And a sample of Remember Me functional test:

def test_login_with_remember_me
    post :login, :username => 'herry', :password => 'passwd',
        :rememberme => '1'
    assert session[:user]
    assert cookies['auth_token']
    assert_response :redirect
    assert_tag :tag => 'div', 
        :child => /[replace with your error message]/

    # reset user session and set request cookie
    session[:user] = nil
    @request.cookies['auth_token'] = cookies['auth_token']    
  
    get :protected_page
    assert_response :success
    assert session[:user]
end

6 Comments . Comments Feed . Trackback URI
Sat, 26 Aug 06 03:18 pm . Brian wrote:

Thank you! I spent an hour trying to track down why my cookie was nil when finally the right combination of keywords (i.e. assert cookie) in google brought me to your post. Time to check if this has been submitted as a patch, at the very least to the documentation.

Sat, 26 Aug 06 11:20 pm . Herryanto Siatono wrote:

Np Brian, glad to be able to help. Okay, I’ll check, and submit a ticket if it has not been reported yet.

Fri, 1 Jun 07 07:35 pm . Fjan wrote:

Thanks for that! I also spent quite a while looking for that disappearing cookie. In integration testing is does work as expected by the way.

Mon, 17 Mar 08 05:55 am . Jason wrote:

It might be worth noting that even if you use cookies[:auth] in your controller, you still need to refer to it as cookies[’auth’] and @request.cookies[’auth’] in the test.

Mon, 13 Oct 08 03:54 pm . Qugstart Blog » Blog Archive » Functional Testing Cookies in Ruby on Rails 1.2.3 wrote:

[…] Here’s a good basic explanation of using cookies on Pluit solutions website.  Then I came across the Robby on Rails blog that led me to understand (and misunderstand) the asssert_cookie plugin. […]

Sun, 30 Nov 08 10:28 am . Gary (aka fool4jesus) wrote:

Thanks very much! I was hitting my head on the wall trying to figure out why my “test_successful_login_with_keep_me_logged_in” method kept failing. :-P

Add Your Comment



(optional)