Question

How do I send a cookie in a functional test? How do I test to be sure that the cookie is cleared?

I've had great success using TDD to build the models for a Rails application, but have hit a snag with regard to controller testing: I can set cookie values once in a test and read them, but I can't clear them. That is:

test "clears cookie" do
  get :set_it, :stuff => {'key' => 'value'} # stuff to cookify
  assert cookies['key'] == 'value' # works fine

  get :clear_it # cookie doesn't get sent. How do I simulate this?
  assert nil == cookies['key'], 'Cookie not cleared' # fails
end

The rails testing guide doesn't mention how to simulate the sending of a cookie in a test, just how to verify that the data were set on the server. I know that I've run into a situation before where the cookie data is not altered on the server until the response is sent. Is that what's happening here? I'd sorta hoped that the functional tests would have done a better job of 'being the client.'

Is this a widely know issue? Are people just resigning themselves to using JUnit for this kind of thing? I'd really love to be able to use one framework for all or nearly all of my tdd.


Sheer desperation and guesswork led me to optimistically try @response.cookies, but that didn't work either.

Was it helpful?

Solution

If you want to have a unit test specifically around the unsetting of a cookie, then you're actually testing if the response contains a header that sets the cookie to nothing. I'm assuming your get :clear_it is doing cookies.delete :cookie-name . This sets response.header to contain Set-[COOKIE-NAME]=;. So if other methods are failing, you could just look for that string directly.

What looks fishy in your code is that you're just checking cookies directly. Where's the response go from your 'get' request?

If all else if failing, you could also use integration tests with webrat as discussed here. This may not be as great as unit testing, but it will at least check the functionality.

OTHER TIPS

My logout test had

assert_nil @response.cookies["auth_token"]

which works.

What value are you getting if not nil?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top