Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test cookies state in functional tests in Rails?

How do I test a given controller action that uses cookies?

How to set cookies in functional tests and how to get them?

like image 930
Szymon Jeż Avatar asked Aug 26 '10 16:08

Szymon Jeż


1 Answers

This is the code that works on Rails 2.3.8 (lines commented out make the test not pass):

test 'cookie testing should work' do
  @request.cookies['foo'] = 'Foo'
  # cookies['foo'] = 'Foo'
  # this does not work to: CGI::Cookie.new('foo', 'bar')
  get :index # does: cookies[:foo] = (cookies['foo'] || "") + " bar!" 
  # the cookie key in the controller can by a symbol, but not in the test
  assert_response :success
  assert_not_nil cookies['foo'], "Cookie with foo key should not be nil. Debug: Cookies=#{cookies.inspect}"
  assert_equal "Foo bar!", cookies['foo'], "Debug: Cookies=#{cookies.inspect}"
  # assert_not_nil @cookies['foo'], "Cookie with foo key should not be nil. Debug: Cookies=#{@cookies.inspect}"
  # assert_not_nil @request.cookies['foo'], "Cookie with foo key should not be nil. Debug: Cookies=#{@request.cookies.inspect}"
  # assert_equal "Foo bar!", @request.cookies['foo'], "Debug: Cookies=#{@request.cookies.inspect}"
end

I have spend some quite long time looking for the answer.

like image 93
Szymon Jeż Avatar answered Nov 14 '22 11:11

Szymon Jeż