我正在尝试使用rspec 2和rails 3在执行GET请求时传递cookie。
到目前为止,我已尝试过以下内容。
get "/", {}, {"Cookie" => "uuid=10"} # cookies[:uuid] is nil
request.cookies[:uuid] = 10 # request is nil
@request.env["Cookie"] = "uuid=10" # @request is nil
helper.request.cookies[:uuid] # helper is not defined
cookies[:uuid] = 10 # cookies[:uuid] is nil
controller.cookies[:uuid] = 10 # cookies is nil
有可能吗?
答案 0 :(得分:2)
我有一个类似的问题,我没有找到适当的解决方案。
rspec-rails docs说明它应该是可能的:
# spec
request.cookies['foo'] = 'bar'
get :some_action
response.cookies['foo'].should eq('modified bar')
在执行get。之前,我的规范request
中的始终为nil
我现在正在嘲笑饼干:
before { ActionDispatch::Request.any_instance.stubs(cookies: {locale: :en}) }
this guy有类似的问题。
答案 1 :(得分:2)
根据this answer,您可以在请求规范中使用cookies
方法:
before { cookies['foo'] = 'bar' }
我尝试了@ phoet的ActionDispatch::Request.any_instance.stubs
解决方案,但它在RSpec 3.4中抛出了一个看似无关的弃用消息错误。
答案 2 :(得分:1)
在wbBuild.generateSW({
globDirectory: '.',
swDest: 'sw_gulp_generated.js',
staticFileGlobs: [
'index.html',
'clear.png'
],
verbose: true,
runtimeCaching: [{
urlPattern: 'https://exapmle.com/file.min.js',
handler: 'staleWhileRevalidate',
options: {
cacheableResponse: {
statuses: [0],
},
},
}]
})
中,您可以使用spec/requests/some_spec.rb
来设置和阅读Cookie。
Rack::Test::Methods
文档:
http://www.rubydoc.info/github/brynary/rack-test/Rack/MockSession#set_cookie-instance_method
答案 3 :(得分:1)
I was a little confused by how you did this at first, but it's actually really easy. Inside of Rails's ActionDispatch::IntegrationTest (or in rspec's case a :request
spec) you have access to a cookies variable.
It works like this:
# set up your cookie
cookies["fruits"] = ["apple", "pear"]
# hit your endpoint
get fruits_path, {}, {}
# this works!
expect(cookies["fruits"]).to eq(["apple", "pear"])
答案 4 :(得分:0)
在RSpec请求测试中对我有用的是显式传递HTTP Cookie标头:
before do
get "/api/books", headers: { Cookie: "auth=secret" }
end