As it is, the signed cookie and encrypted cookie cannot be accessed in the request spec. Specifically, I get the following error.
NoMethodError:
undefined method `signed' for #<Rack::Test::CookieJar:0x00007fbc6751fa38>
This is because the cookies object used in the request spec is an instance of Rack :: Test :: CookieJar
instead of ʻActionDispatch :: Cookies :: CookieJar and implements the
signed and ʻencrypted
methods. Because it is not.
ʻUse ActionDispatch :: Cookies :: CookieJar`.
it do
get some_url
expect(response).to have_http_status(:success)
jar = ActionDispatch::Cookies::CookieJar.build(request, cookies.to_hash) #here
expect(jar.signed['foo']).to eq('something') #signed cookie too
expect(jar.encrypted['bar']).to eq('something_else') #Encrypted cookies can also be read
end
However, this alone will not work in the case of secure: true
(setting to send cookies only to https server). (The part of jar.signed ['foo']
becomes nil
)
cookies.signed[:foo] = {
value: 'your_value_comers_here',
expires: 1.day.from_now,
secure: true, #This setting
httponly: true
}
In that case, don't use secure: true
in the development
and test
environments.
def method_that_uses_cookie
foo = 'foo'
cookies.encrypted[:foo] = build_cookies(foo)
end
def build_cookies(value)
cookie = {
value: value,
expires: 1.day.from_now,
httponly: true
}
if Rails.env.development? || Rails.env.test?
cookie
else
cookie.merge(secure: true)
end
end
As a supplementary alternative to ↑, I also tried running rspec in ssl mode.
protocol:'https: //'
and protocol:: https as described in https://stackoverflow.com/questions/6785261/test-an-https-ssl-request-in-rspec-rails I tried'
, but it didn't work.
It seems that protocol
is not supported by rspec in the first place because it says ʻArgumentError: unknown keyword: protocol`.
I referred to this article. https://philna.sh/blog/2020/01/15/test-signed-cookies-in-rails/