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 和 cookies 的所有内容都与控制器有关。有什么方法可以在 Rspec 辅助测试中获取/设置 cookie?
(Rspec/Rspec-rails 2.5、Rails 3.0.4)
谢谢!
更新:
找到了关于如何设置cookie的答案,所以我将其留在这里供其他人参考。
我正在寻找的作品:
helper.request.cookies[:awesome] = "something"
仍然不知道如何获取饼干......
Helper Method
# Determine if this is user's first time
def first_time?
cookies[:first_time].nil?
end
Attempted Rspec test
it "returns true if the cookie is set" do
cookies[:first_time] = "something"
helper.first_time?().should be(true)
end
Error:
undefined method `cookies' for nil:NilClass
Everything I've read about Rspec and cookies has to do with the controller. Any way to get/set cookies in Rspec helper tests?
(Rspec/Rspec-rails 2.5, Rails 3.0.4)
Thanks!!
UPDATE:
Found an answer on how to SET cookies, so I'll leave it here for other's reference.
the piece I was looking for:
helper.request.cookies[:awesome] = "something"
Still don't know how to GET cookies...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我能找到的最好的解释是在这里: https://www.relishapp .com/rspec/rspec-rails/docs/controller-specs/cookies
引用:
例子:
The best explanation I've been able to find is here: https://www.relishapp.com/rspec/rspec-rails/docs/controller-specs/cookies
Quoted:
Example:
我刚刚偶然发现了你的问题(我正在寻找答案)。我成功地尝试了这个:
I just stumbled upon your question (I was looking for an answer). I tried this successfully:
在 Rails 6.1.3 上,没有一个答案对我有用,但经过多次测试,以下方法有效:
对于签名的 cookie:
None of the answers worked for me on Rails 6.1.3, but after much testing, the following worked:
And for signed cookies:
您获取 cookie 的方式与设置它们的方式相同。我的一项规格示例:
You get the cookies the same way you set them. Example from one of my specs:
在控制器测试中,这是有效的:
在 before 块中。
我在此处找到了这个
In a controller test this works:
in a before block.
I found this here