Rails functional testing quirks with Flash and Session

Here’s an interesting behavior I found today. When I say interesting, I mean really, really annoying. It took me all afternoon to find this out.

Here’s a rough idea of my test:

  get :index
  assert something
  get :change_something
  assert flash[:notice] = "Something changed"

This works fine, but then I made a change to pass session data to the ‘get’ calls – no other code in the system changes

  get :index, nil, { :user => "foo" }
  assert something
  get :change_something, nil, { :user => "foo" }
  assert flash[:notice] = "Something changed"

Suddenly, the last assert fails. What happened?

With some poking around, I find that ‘flash’ returns an empty hash. Breakpoint really helps to see that the flash is set in my action, but is gone by the time my assert call is made.

Looking much deeper, I find this code in the code to process the HTTP methods

  @request.session = ActionController::TestSession.new(session) unless session.nil?
  @request.session["flash"] = ActionController::Flash::FlashHash.new.update(flash) if flash

If I pass session parameters to my HTTP get, then the entire session is wiped out and re-initialized using the parameters. Also, the flash seems to also be stored in the session object.

When the session is re-initialized, the flash entry is removed, and the Rails flash handling code starts adding the flash entry to the controller’s @flash member instead of the session[‘flash’]

The code that does this is here.

  @flash = 
    if @session.is_a?(Hash)
      FlashHash.new
    else
      @session["flash"] ||= FlashHash.new
    end  

If the flash gets wiped out, a new one is created that, if the session is a plain Hash, is not added to the session.

No errors occur, there is no warning, but the code has changed behavior in a non-obvious way between calls.

This entry was posted on Thu, 11 May 2006 07:56:00 GMT . You can follow any any response to this entry through the Atom feed. You can leave a comment or a trackback from your own site.
Tags


Trackbacks

Use the following link to trackback from your own site:
http://blog.craz8.com/trackbacks?article_id=rails-functional-testing-quirks-with-flash-and-session&day=11&month=05&year=2006

Comments

Leave a response

Leave a comment