当我登录到我的应用程序时,服务器会发回 cookie(凭据和某些应用程序的 cookie):
Response sent 170 bytes of Cookie data:
Set-Cookie: user_credentials=val; path=/; HttpOnly; Secure
Response sent 554 bytes of Cookie data:
Set-Cookie: _app_session=otherVal; path=/; HttpOnly; Secure
...然后重定向到主页;
Cookie 包含一些标志:例如httpOnly
、Secure
等
我如何测试 cookie 是否包含那些带有 Rspec 的标志?
至少我在哪里可以找到这些 cookie?
it "should generate cookies with proper flags" do
params = Factory.attributes_for(:user,
:username => "uname",
:password => "upass"
)
# login
post 'create', params
response.should redirect_to home_url # => pass
puts "response cookie = #{response.cookies.inspect}" # => {} // no cookies in response, why?
end
最佳答案
Controller 规范不会生成/调用真正的 http 请求,它们只是设置被测 Controller 并在其上调用请求的操作。没有发出 http 请求,也没有生成真正的 http 应答。因此,您只能在更抽象的层面上测试 Rails Controller 的内部工作。
这些规范中的 cookie 处理相当简单,在这样的操作中设置 cookie:
def set_cookies
cookies[:foo] = 'bar'
cookies[:lorem] = {:value => 'ipsum', :expires => 3.days.from_now}
render :nothing => true
end
生成规范中可访问的以下值:
it "should set some cookie values" do
get :set_cookies
# response.cookies looks like this:
# {'foo' => 'bar', 'lorem' => 'ipsum'}
response.cookies['foo'].should == 'bar'
response.cookies['lorem'].should == 'ipsum'
end
要测试您在响应中看到的那种 cookie 标志,您必须使用执行真实 http 请求的东西。或许你可以使用 capybara gem ?
关于ruby-on-rails - 使用 Rspec v.1 测试响应 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13008922/