如何在 Rails 的功能测试中测试 cookie 状态?

发布于 2024-09-16 03:20:01 字数 61 浏览 1 评论 0原文

如何测试使用 cookie 的给定控制器操作?

功能测试中如何设置cookie以及如何获取?

How do I test a given controller action that uses cookies?

How to set cookies in functional tests and how to get them?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

天暗了我发光 2024-09-23 03:20:01

这是在 Rails 2.3.8 上运行的代码(注释掉的行使测试无法通过):

test 'cookie testing should work' do
  @request.cookies['foo'] = 'Foo'
  # cookies['foo'] = 'Foo'
  # this does not work to: CGI::Cookie.new('foo', 'bar')
  get :index # does: cookies[:foo] = (cookies['foo'] || "") + " bar!" 
  # the cookie key in the controller can by a symbol, but not in the test
  assert_response :success
  assert_not_nil cookies['foo'], "Cookie with foo key should not be nil. Debug: Cookies=#{cookies.inspect}"
  assert_equal "Foo bar!", cookies['foo'], "Debug: Cookies=#{cookies.inspect}"
  # assert_not_nil @cookies['foo'], "Cookie with foo key should not be nil. Debug: Cookies=#{@cookies.inspect}"
  # assert_not_nil @request.cookies['foo'], "Cookie with foo key should not be nil. Debug: Cookies=#{@request.cookies.inspect}"
  # assert_equal "Foo bar!", @request.cookies['foo'], "Debug: Cookies=#{@request.cookies.inspect}"
end

我花了很长时间寻找答案。

This is the code that works on Rails 2.3.8 (lines commented out make the test not pass):

test 'cookie testing should work' do
  @request.cookies['foo'] = 'Foo'
  # cookies['foo'] = 'Foo'
  # this does not work to: CGI::Cookie.new('foo', 'bar')
  get :index # does: cookies[:foo] = (cookies['foo'] || "") + " bar!" 
  # the cookie key in the controller can by a symbol, but not in the test
  assert_response :success
  assert_not_nil cookies['foo'], "Cookie with foo key should not be nil. Debug: Cookies=#{cookies.inspect}"
  assert_equal "Foo bar!", cookies['foo'], "Debug: Cookies=#{cookies.inspect}"
  # assert_not_nil @cookies['foo'], "Cookie with foo key should not be nil. Debug: Cookies=#{@cookies.inspect}"
  # assert_not_nil @request.cookies['foo'], "Cookie with foo key should not be nil. Debug: Cookies=#{@request.cookies.inspect}"
  # assert_equal "Foo bar!", @request.cookies['foo'], "Debug: Cookies=#{@request.cookies.inspect}"
end

I have spend some quite long time looking for the answer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文