如何使用 rspec 测试签名或永久 cookie?

发布于 2024-12-10 09:54:47 字数 452 浏览 0 评论 0原文

我可以将 cookie 写入请求中:

request.cookies['foo'] = 'bar'

但是这些都不起作用:

request.cookies.permanent['foo'] = 'bar'
request.cookies.signed['foo'] = 'bar'
request.cookies.permanent.signed['foo'] = 'bar' # what I really want

我收到空的哈希消息,例如这样的消息:

NoMethodError:
    undefined method `signed' for {}:Hash

如何为我的测试创建这些 cookie?

我使用的是 Rails 3.1 和 rspec 2.6.0。

I can write cookies to the request fine with:

request.cookies['foo'] = 'bar'

But none of these work:

request.cookies.permanent['foo'] = 'bar'
request.cookies.signed['foo'] = 'bar'
request.cookies.permanent.signed['foo'] = 'bar' # what I really want

I get empty hash messages like messages like this:

NoMethodError:
    undefined method `signed' for {}:Hash

How can I create these cookies for my tests?

I am using rails 3.1 and rspec 2.6.0.

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

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

发布评论

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

评论(2

清风疏影 2024-12-17 09:54:47

使用

cookies.permanent['foo'] = 'bar'
cookies.signed['foo'] = 'bar'
cookies.permanent.signed['foo'] = 'bar' 

替代

Use

cookies.permanent['foo'] = 'bar'
cookies.signed['foo'] = 'bar'
cookies.permanent.signed['foo'] = 'bar' 

Instead

记忆之渊 2024-12-17 09:54:47

假设您有以下 Rails 助手:

module ApplicationHelper
  def set_cookie(name, value)
    cookies.permanent.signed[name] = value
  end
end

要使用 RSpec 2.11.0Rails 3.2.6 中测试它,您可以执行以下操作:

require 'spec_helper'

describe ApplicationHelper do
  it "should set a permanent, signed cookie" do
    cookies.should_receive(:permanent).once.and_return(cookies)
    cookies.should_receive(:signed).once.with(:user_id, 12345)
    helper.set_cookie(:user_id, 12345)
  end
end

我从未遇到过使用问题rspec 来测试 cookies.signed[:foo].should == 'bar',但是调用 cookies.permanent 在过去给我带来了问题。上面,我实际上只是对 permanent 方法进行存根操作并再次返回 cookies 对象。这使我可以测试它是否已被调用。

您确实不必担心天气导轨本身设置永久 cookie,因为它已经过测试。

Say you have the following Rails helper:

module ApplicationHelper
  def set_cookie(name, value)
    cookies.permanent.signed[name] = value
  end
end

To test this in Rails 3.2.6 using RSpec 2.11.0, you could do the following:

require 'spec_helper'

describe ApplicationHelper do
  it "should set a permanent, signed cookie" do
    cookies.should_receive(:permanent).once.and_return(cookies)
    cookies.should_receive(:signed).once.with(:user_id, 12345)
    helper.set_cookie(:user_id, 12345)
  end
end

I've never run into problems using rspec to test cookies.signed[:foo].should == 'bar', but throwing in a call to cookies.permanent has given me problems in the past. Above, I'm really just stubbing the permanent method and returning the cookies object again. This allows me to test that it has been called.

You really shouldn't have to worry about weather rails itself set a permanent cookie because that has been tested already.

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