[rspec-users] Cookies - how to set in controller specs?

David Chelimsky dchelimsky at gmail.com
Wed Jul 2 07:06:38 EDT 2008

On Tue, Jul 1, 2008 at 6:37 PM, Christopher Bailey <chris at cobaltedge.com> wrote:
> I've been searching Google, the mailing list, etc, etc. and can't for
> the life of me get a cookie to be set in a controller spec.  From
> everything I've read on the web, it appears all I need to do is the
> typical:
>  cookies[:name] = value
> or
>  cookies[:name] = { :value => something, :expires => 1.year.from_now }
> I have also see things like doing "@request.cookies[:name]..." or
> setting the value to doing CGI::Cookie.new(...), and so on.
> I do not want to mock cookies, I want to actually test them, as that
> is the logic I'm trying to test.  I know that my actual code works as
> I've run through this by directly testing in the browser, but of
> course I want specs to test it.  Can someone show a test of setting a
> cookie, getting a page/action (and then optionally testing cookie
> after that)?

This is just one of those goofy things in Rails testing. I'm not sure
the best way to make it easier in rspec without breaking existing
examples in the process. Regardless, here's how you interact with
cookies from an example:

To set a cookie:

  request.cookies[:cookie_key] = CGI::Cookie.new('cookie_key', 'cookie value')

To read a cookie

  response.cookies[:cookie_key].should == ["expected value"]


  cookies[:cookie_key].should == ["expected value"]

Rails provides a cookies object that is actually response.cookies, so
you don't *have* to reference it through the response object. I would,
however, as I've been known to try to set a cookie in an example using
cookies when I should have been using request.cookies. So I try to
keep them explicit.


More information about the rspec-users mailing list