Using Cookies with Rack::Test
Asked Answered
C

1

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?

Circumnutate answered 17/3, 2011 at 5:20 Comment(0)
M
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.

Mensurable answered 17/3, 2011 at 8:29 Comment(7)
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)Circumnutate
UPD. rack_mock_session.cookie_jar["foo"] is not empty only in one post, on next test it's empty.Circumnutate
UPD. worked around by storing cookie in global var, so before each request i set cookie.Circumnutate
I updated the answer with a possible solution to your problem.Mensurable
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.Penland
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 outIntern
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?Yankeeism

© 2022 - 2024 — McMap. All rights reserved.