Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Cookies with Rack::Test

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?

like image 922
Andoriyu Avatar asked Mar 17 '11 05:03

Andoriyu


1 Answers

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.

like image 162
Miikka Avatar answered Sep 21 '22 15:09

Miikka