metkat metkat - 4 months ago 21
Ruby Question

How do I set a cookie for an integration test in Rails?

I have general application behavior that changes based on cookie contents, and need to test it. As an example, if a user doesn't have a cookie set indicating that they've accepted the site's legal terms, they need to be redirected to the T&C page.

I can set a cookie in a functional test using

request.cookies["legal_accepted"] = "yes"


However, this will not work in an integration test- there's no request object to work with. I've been unable to find any documentation of why this is so, what else is different, and best practices for working with the difference. How can I set a cookie for a given request? Is the why and wherefore documented anywhere?

Answer

The only way I have found to do this is to set the cookie header manually in the request, e.g.

get "/", {}, { "HTTP_COOKIE" => "legal_accepted=yes; cookie2=value2; "}