2012-07-03 47 views
5

传递cookies我试图做一个GET请求时,通过一个cookie,使用rspec的2和3,轨道在要求规范

我已经试过到目前为止以下。

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 

这可能吗?

回答

2

我有一个类似的问题,我没有找到一个适当的解决方案。

rspec-rails docs状态,它应该是可能的:

# spec 
request.cookies['foo'] = 'bar' 
get :some_action 
response.cookies['foo'].should eq('modified bar') 

在我的规格request总是nil执行之前把。

我现在嘲讽饼干:

before { ActionDispatch::Request.any_instance.stubs(cookies: {locale: :en}) } 

this guy有类似的问题。

+0

您链接到是控制器的规格,不得要求规范,这就是为什么'request'回报'nil'的文档。还试图找出如何在RSpec 3.4中做到这一点。 –

1

this answer,你可以要求规范内使用cookies方法:

before { cookies['foo'] = 'bar' } 

我试过涉及ActionDispatch::Request.any_instance.stubs @ phoet的解决方案,但它与RSpec的3.4看似无关的折旧消息一起抛出一个错误。

0

我对你是怎么做到这起初有点困惑,但它实际上是很容易的。在Rails的ActionDispatch :: IntegrationTest(或rspec的情况下,:request规范)中,您可以访问cookie变量。

它的工作原理是这样的:

# set up your cookie 
cookies["fruits"] = ["apple", "pear"] 

# hit your endpoint 
get fruits_path, {}, {} 

# this works! 
expect(cookies["fruits"]).to eq(["apple", "pear"])