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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…