How can I check signed or persistent cookies with rspec?

I can write cookies on request with:

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

But none of these works:

 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 such as 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.

+4
source share
2 answers

Use

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

Instead

+5
source

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 can 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 have never encountered problems using rspec to test cookies.signed[:foo].should == 'bar' , but challenging cookies.permanent given me problems in the past. Above, I actually just cheats on the permanent method and returns the cookies object again. This allows me to verify that it was called.

You really don't have to worry about the weather rails setting a permanent cookie themselves, because it has already been verified.

0
source

All Articles