使用Cookie与Rack :: Test [英] Using Cookies with Rack::Test
问题描述
我想使用Rack :: Test为我的Sinatra应用程序编写RSpec测试。我不明白如何使用cookies。例如,如果我的应用程序设置cookie(不通过:会话)如何检查该cookie是否正确设置?
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?
此外,如何使用该Cookie发送请求?
Also, how can I send requests with that cookie?
推荐答案
Rack :: Test保持一个持久化请求的cookie jar。您可以使用 rack_mock_session.cookies
访问它。假设您有这样的处理程序:
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
您也可以使用 last_request.cookies
,但是如名字所示,它包含最后一个请求的cookie,而不是响应。您可以使用 set_cookie
设置Cookie,然后使用 clear_cookies
清除Cookie。
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
更新: ( it
块),您需要在执行任何测试用例之前初始化Rack会话。为此,请将之前
添加到 describe
块。
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
b $ b
或者,您可以使用之前:每个
在每个请求之前设置必要的Cookie。
Alternative, you could for example use before :each
to set up the necessary cookies before each request.
这篇关于使用Cookie与Rack :: Test的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!