[rspec-users] Cookie value set in spec, but controller can't read it

David Chelimsky dchelimsky at gmail.com
Tue Jan 11 11:33:38 EST 2011


On Jan 10, 2011, at 8:27 AM, Marko Anastasov wrote:

> On Mon, Jan 10, 2011 at 05:05, David Chelimsky wrote:
>> On Jan 5, 2011, at 11:54 AM, Marko Anastasov wrote:
>> 
>>> Hello,
>>> 
>>> I set a value in controller spec using @request.cookies:
>>> https://gist.github.com/371356ba0a19666fd3b5
>>> 
>>> but when the controller reads it, it's nil somehow, as this screenshot
>>> from the debugger shows:
>>> http://dl.dropbox.com/u/830772/p/Selection_033.jpeg
>>> 
>>> This does not occur in development environment. I'm using RSpec 2.4
>>> and Rails 3.
>>> 
>>> Does someone have an idea what I am doing wrong / how to solve this?
>> 
>> That looks like it should work, and I don't think you're doing anything wrong.
>> 
>> What's happening is that the object returned by @request.cookies is a Hash, but the object returned by cookies() in the controller is an ActionDispatch::Cookies::CookieJar. If you print them both out with .inspect, they'll both say they are {:lastfm_username => "rj"}, but the answer differently to other questions:
>> 
>> # in spec
>> @request.cookies[:lastfm_username] # => "rj"
>> @request.cookies["lastfm_username"] # => nil
>> 
>> # in controller
>> cookies[:lastfm_username] # => nil
>> cookies["lastfm_username"] # => nil
>> 
>> You'll see exactly the same behavior, btw, in a Rails functional test (which an RSpec controller spec wraps), so this is happening in the Rails test infrastructure, not RSpec. Care to log a bug report in the Rails tracker?
>> 
>> https://rails.lighthouseapp.com/
>> 
> 
> Thanks for your explanation David. I created Rails ticket #6272.
> 
> Later I found a workaround of using request.cookies in the controller,
> but it would be nice if it would just work with cookies.
> 
> Btw I was also not sure when to use symbols, and when keys. Eg if I
> set a value in controller:
> cookies.permanent[:lastfm_username] = username
> 
> then in spec, I need to obtain the value with a string:
> cookies["lastfm_username"].should == "rj"

My understanding is that it's a HashWithIndifferentAccess, which means you can use string or symbol keys. That said, however, when the app is running the cookies come from the rack environment and are always string keys, so I'd recommend sticking w/ that for consistency, but that's a pretty subjective thing.


HTH,
David


More information about the rspec-users mailing list