Ian
Ian

Reputation: 4185

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?

Upvotes: 6

Views: 2440

Answers (4)

Ivko Maksimovic
Ivko Maksimovic

Reputation: 36

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

Upvotes: 0

Bill
Bill

Reputation: 31

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

Upvotes: 2

uberllama
uberllama

Reputation: 21358

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

Upvotes: -2

Polemarch
Polemarch

Reputation: 1646

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)

Upvotes: 8

Related Questions