Cookie Testing Quirks in Rails
I documented about a gotcha with cookie testing in rails recently. Today I found another one.
After the test call, you can assert cookie value as:
should "set some cookie properly" do # 1. setup test data ... # 2. perform test ... # 3. assert search result assert_not_nil cookies['auth_token'] end
However, when setting up test data, you can NOT use “cookies” call.
should "do something based on an existing cookie" do # 1. setup test data (the following line will not fail at runtime but it won't work as expected - it won't set the cookie) cookies['remember_me_token'] = "fqpoei13w0123" # 2. perform test ... # 3. assert search result assert_successful_autologin # assertion will fail end
You have to use either controller.request.cookies or @request.cookies:
should "do something based on an existing cookie" do # 1. setup test data (use controller.request.cookies or @request.cookies) controller.request.cookies['remember_me_token'] = "fqpoei13w0123" # 2. perform test ... # 3. assert search result assert_successful_autologin # this will work end
I dug a little into rails code to see what could be the reason and if it could be improved and I found this:
class ActionController::TestCase include TestProcess end module TestProcess def session @request.session end def flash @response.flash end def cookies @response.cookies end end
As we can see the cookies method is returning the response cookies and not request cookies. Also, session call returns @request.session which is the same for both request/response.
For cookies, they had to pick one and they chose Response. For simplicity, I would not use cookies call, and just use controller.request.cookies and controller.response.cookies. The tests are more understandable/maintainable that way.
Now I know!
Related posts:
- Getting session_id in rails If you are using database sessions, rails sessions table stores...
- Ruby Authlogic: lazy initialization based on defined?() call What is the difference between following two versions of code?...
- Rails Email Unit Testing ActionMailer classes, for sending out emails, typically reside with...
- Working with Authlogic in script/console When probing / debugging issues with Authlogic on rails console,...
- Environment specific routing in rails For better application support, it is usually nice to build...
Related posts brought to you by Yet Another Related Posts Plugin.





