2011-03-29 107 views
19

helper方法Rspec的:在一个辅助测试设置cookie

# Determine if this is user's first time 
    def first_time? 
    cookies[:first_time].nil? 
    end 

试图Rspec的测试

it "returns true if the cookie is set" do 
    cookies[:first_time] = "something" 
    helper.first_time?().should be(true) 
end 

错误:

undefined method `cookies' for nil:NilClass 

一切我读过有关Rspec的饼干有与控制器做。在Rspec助手测试中获取/设置cookie的任何方式?

(Rspec的/ Rspec的护栏2.5,Rails的3.0.4)

谢谢!

UPDATE:

找到如何设置cookies的答案,所以我会在这里把它留给其他的参考。

这块我一直在寻找:

helper.request.cookies[:awesome] = "something" 

还是不知道怎么弄饼干...

+0

只是好奇,你为什么会想饼干?在规格中,您始终是设置Cookie的人,所以您知道他们是什么。你不是只想测试一下你的应用程序是否以某种方式按照某种方式设置了cookies? – radixhound 2012-08-04 15:35:25

+0

GET只是'helper.request.cookies [:awesome]' – 2016-04-20 22:13:02

回答

17

我已经能够找到的最好的解释是在这里:https://www.relishapp.com/rspec/rspec-rails/docs/controller-specs/cookies

报价:

Recommended guidelines for rails-3.0.0 to 3.1.0

  • Access cookies through the request and response objects in the spec.
  • Use request.cookies before the action to set up state.
  • Use response.cookies after the action to specify outcomes.
  • Use the cookies object in the controller action.
  • Use String keys.

例如:

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

# controller 
def some_action 
    cookies['foo'] = "modified #{cookies['foo']}" 
end 
+0

还要注意,如果您使用像'cookies [:foo] = true'这样的符号设置cookie,您将拥有密钥并且值转换为字符串'cookies ['foo'] ='true'' – Calin 2013-10-28 14:07:03

0

你得到的cookies,您将它们设置相同的方式。从我的规格的一个例子:

request.cookies[:email].should be nil 
+1

奇怪。如果我把它放在我的帮助器规范中,我会得到“未定义的局部变量或方法'请求'”。如果我将它更改为helper.request,我会得到零(尽管它在功能上工作正常,代码也很实用)。哎呀。 – jmccartie 2011-04-01 04:14:01

+0

这里是我试图运行的规范及其结果:https://gist.github.com/897722 – jmccartie 2011-04-01 04:19:33

2

我只是偶然发现了你的问题(我正在寻找答案)。我想这成功:

helper.request.cookies[:foo] = "bar" 
0

在控制器测试工作的:

@request.cookies[:cookie_name] = "cookie_value" 

块之前。

我发现这个here