ruby-on-rails - Rspec:在辅助测试中设置 cookie

标签 ruby-on-rails rspec rspec2

辅助方法

  # 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 和 cookie 的所有内容都与 Controller 有关。在 Rspec 辅助测试中获取/设置 cookie 的任何方法?

(Rspec/Rspec-rails 2.5, Rails 3.0.4)

谢谢!!

更新:

找到了关于如何设置 cookie 的答案,所以我将其留在这里以供其他人引用。

我正在寻找的作品:
helper.request.cookies[:awesome] = "something"

仍然不知道如何获取cookie...

最佳答案

我能找到的最好的解释在这里: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

关于ruby-on-rails - Rspec:在辅助测试中设置 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5475989/

相关文章:

Ruby rspec 测试命令 : could not locate Gemfile

javascript - 如何刷新div而不重新加载整个页面?

ruby RSpec "no such file to load"错误

javascript - 访问 javascript 或 jquery 文件中的 Controller / View 实例变量

rspec - 有没有办法让 Capybara 在浏览器中进行实时测试?

ruby-on-rails - 为布局中使用的部分编写规范

ruby-on-rails - 使用 Rspec GET 发送格式

ruby-on-rails - Rspec with rails 3.1 给出了弃用警告 ActiveRecord::Associations::AssociationCollection 已弃用?

ruby-on-rails - 不理解在 Rails 中使用 Grape API gem 的嵌套资源

ruby-on-rails - 关于 'delayed_job'的一些基本问题