5

I can't figure out how to test that a cookie has been set when testing my helper method.

Hypothetical helper method:

def my_helper(k,v)
    cookies[k] = v
end

Test:

it 'should set cookies' do  
  helper.my_helper("foo", "bar")
  helper.cookies["foo"].should == "bar" #nil
  helper.response.cookies["foo"].should == "bar" #nil
end

Anyone know how to do this?

Matt Baker
  • 3,694
  • 1
  • 20
  • 16
  • http://stackoverflow.com/questions/5475989/rspec-setting-cookies-in-a-helper-test here, always do your homework! – Rodrigo Zurek Jul 25 '12 at 22:05
  • I saw that post, as the OP mentions, he's still not sure how to _get_ cookies. – Matt Baker Jul 25 '12 at 22:15
  • According to the rspec docs `response.cookies["foo"]` should work but I'm on rails 3.2 and rspec 2.8 and it does not work for me. https://www.relishapp.com/rspec/rspec-rails/docs/controller-specs/cookies. As far as I can tell there's something strange going on between rspec, rails integration tests, and rack which makes this hard to figure out. – Dty Jul 26 '12 at 00:39

3 Answers3

4

Substituting a simple rspec mock for the CookieJar works, if you're willing to:

helper.stubs(:cookies => cookies = mock)
cookies.expects(:[]=).with('foo', 'bar')
helper.my_helper('foo', 'bar')
jaredjacobs
  • 5,625
  • 2
  • 27
  • 23
2

I'm on rails 3.2 and rspec 2.8. Despite what the rspec docs says the following works for me in a request spec (ie. integration test).

it 'should set cookies' do  
  cookies['foo'] = 'bar'
  visit "/"
  cookies['foo'].should == 'bar'
end
Dty
  • 12,253
  • 6
  • 43
  • 61
  • Yup, I've definitely checked cookies in standard request specs. – Matt Baker Jul 26 '12 at 00:52
  • @MattBaker Which version of rails and rspec you're using? – Dty Jul 26 '12 at 00:59
  • @MattBaker also here an article about how someone debugged their way through using cookies in rspec. It might help you figure out how to troubleshoot this whole thing. http://dobbse.net/thinair/2011/12/capybara-racktest-rspec-cookies-2of2.html – Dty Jul 26 '12 at 01:01
  • We're on rails 3.1.4 and rspec 2.8. Maybe I'll take a shot at upgrading. – Matt Baker Jul 26 '12 at 01:13
0

request the cookie through

 helper.request.cookies[:awesome] = "something"
Rodrigo Zurek
  • 4,555
  • 7
  • 33
  • 45