blu
blu

Reputation: 13175

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 method `signed' for {}:Hash

How can I create these cookies for my tests?

I am using rails 3.1 and rspec 2.6.0.

Upvotes: 5

Views: 2623

Answers (2)

user1470598
user1470598

Reputation: 47

Use

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

Instead

Upvotes: 3

bschaeffer
bschaeffer

Reputation: 2904

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.

Upvotes: 0

Related Questions