Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing signed cookies in rails

I'm using signed cookies in Rails 3 to enable a "remember-me" feature in an application. Everything works except I'm not able to functional test the cookies, since comparing cookies['remember_id'] gives me the encrypted cookie, and cookies.signed is not defined.

Any clues?

like image 247
Ian Avatar asked Feb 23 '11 21:02

Ian


2 Answers

The problem (at least on the surface) is that in the context of a functional test (ActionController::TestCase), the "cookies" object is a Hash, whereas when you work with the controllers, it's a ActionDispatch::Cookies::CookieJar object. So we need to convert it to a CookieJar object so that we can use the "signed" method on it to convert it to a SignedCookieJar.

You can put the following into your functional tests (after a get request) to convert cookies from a Hash to a CookieJar object

@request.cookies.merge!(cookies)
cookies = ActionDispatch::Cookies::CookieJar.build(@request)
like image 194
Polemarch Avatar answered Sep 21 '22 09:09

Polemarch


This is slightly off-topic, but I was having trouble getting the Rails 3 solution to work in Rails 5 because ActionDispatch::Cookies::CookieJar.build has changed. This did the trick:

jar = ActionDispatch::Cookies::CookieJar.build(@request, cookies.to_hash)
assert_equal jar.signed['remember_token'], ...
like image 29
Bill Avatar answered Sep 20 '22 09:09

Bill