13

I'm trying to write RSpec tests for my Sinatra application using Rack::Test. I can't understand how I can use cookies. For example if my application set cookies (not via :session) how can I check whether that cookie is properly set?

Also, how can I send requests with that cookie?

Brett Hardin
  • 4,012
  • 2
  • 19
  • 22
Andoriyu
  • 212
  • 7
  • 17

1 Answers1

20

Rack::Test keeps a cookie jar that persists over requests. You can access it with rack_mock_session.cookies. Let's say you have a handler like this:

get '/cookie/set' do
    response.set_cookie "foo", :value => "bar"
end

Now you could test it with something like this:

it 'defines a cookie' do
    get '/'
    rack_mock_session.cookie_jar["foo"].should == "bar"
end

You can also access cookies with last_request.cookies, but as the name says, it contains the cookies for the last request, not the response. You can set cookies with set_cookie and clear them with clear_cookies.

it 'shows how to set a cookie' do
   clear_cookies        
   set_cookie "foo=quux"
   get '/'
   last_request.cookies.should == {"foo" => "quux"}
end

Update: If you want the cookie jar to persist across the test cases (it blocks), you need to initialize the Rack session before executing any test cases. To do so, add this before hook to your describe block.

before :all do
    clear_cookies
end

Alternative, you could for example use before :each to set up the necessary cookies before each request.

Miikka
  • 4,573
  • 34
  • 47
  • Ok, now I see that cookie is properly set, but when I do request to route that require valid cookie — I got error. (server returns 401 error if cookie is not set or incorrect) – Andoriyu Mar 18 '11 at 06:49
  • UPD. rack_mock_session.cookie_jar["foo"] is not empty only in one post, on next test it's empty. – Andoriyu Mar 18 '11 at 06:57
  • UPD. worked around by storing cookie in global var, so before each request i set cookie. – Andoriyu Mar 18 '11 at 07:00
  • I updated the answer with a possible solution to your problem. – Miikka Mar 18 '11 at 09:32
  • 3
    It's probably not a good idea to have the cookie jar persist across tests, as then your tests are dependent on the order in which they are run (and you can't run individual tests when they break). If you need to do the same _arrange_ steps in many tests (before you _act_ and _assert_) then you are probably better off writing helper methods which you can call in a `before :each` block. – JP. Aug 04 '15 at 17:16
  • I've had some trouble checking if the cookie was properly set using the approach mentioned on this topic, if you happen to be in the same situation, please check this [answer](http://stackoverflow.com/a/43623293/1463744) out – fagiani Apr 26 '17 at 01:06
  • I can't really find much documentation on how to use sessions and cookies in Rack. Can someone please point me to a website that explains this extensively? – thiebo Jan 30 '21 at 20:28