开发者

How can I test signed or permanent cookies with rspec?

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开发者_Go百科 method `signed' for {}:Hash

How can I create these cookies for my tests?

I am using rails 3.1 and rspec 2.6.0.


Use

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

Instead


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜