开发者

Testing signed cookies in rails

I'm using signed cookies in Rails 3 to enable a "remember-me" f开发者_C百科eature 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?


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)


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'], ...


This will convert all encrypted and signed cookies to the regular ones for test environment. Just make sure you don't have cookies with secure attribute (won't work)

In config/initializers/signed_cookies_patch_test.rb:

if Rails.env.test?
  class ActionDispatch::Cookies::CookieJar
    def encrypted; self; end
    def signed; self; end
  end
end


assert_equal @controller.send(:cookies).signed[:remember_id], matching_value

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜