Rspec:在辅助测试中设置 cookie
辅助方法
# Determine if this is user's first time
def first_time?
cookies[:first_time].nil?
end
尝试 Rspec 测试
Attempted Rspec test
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 和 cookie 的所有内容都与控制器有关.在 Rspec 辅助测试中获取/设置 cookie 的任何方法?
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)
(Rspec/Rspec-rails 2.5, Rails 3.0.4)
谢谢!!
更新:
找到了关于如何设置 cookie 的答案,所以我将其留在这里以供其他人参考.
Found an answer on how to SET cookies, so I'll leave it here for other's reference.
我正在寻找的作品:
helper.request.cookies[:awesome] = "something"
仍然不知道如何获取 cookie...
Still don't know how to GET cookies...
我能找到的最好的解释在这里: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
引用:
rails-3.0.0 到 3.1.0 的推荐指南
Recommended guidelines for rails-3.0.0 to 3.1.0
- 通过请求和响应对象访问 cookie规范
- 在操作前使用 request.cookies 来设置状态.
- 在操作后使用 response.cookies 来指定结果.
- 在控制器操作中使用 cookie 对象.
- 使用字符串键.
示例:
# 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