Darwinweb

Dry Up Functional Tests with @request.session

July 4, 2007     

Do you ever end up with every one of your 50 functional tests have a line something like this?


get :index, nil, :user_id => users(:one).id

Not only is it a lot of repetition, but you also have to put in a placeholder nil, or explicitly wrap your params hash in curly braces to separate it from the session. Not every app is like this, but if yours is you might appreciate knowing that you can pre-populate the session in your test’s setup method. Something like this (boilerplate included):


  def setup
    @controller = MyController.new
    @request    = ActionController::TestRequest.new
    @response   = ActionController::TestResponse.new

    @request.session[:user_id] = users(:one).id
  end

If the majority of the tests in a given test class require the same user, this can be very handy. In my case, I have an app where the functional tests are actually split up and namespaced by user class, so this technique gives me a double bonus. But remember you can always override this preset like this:


get :index, nil, :user_id => nil