Peter Marklund

Peter Marklund's Home

Mon Oct 01 2007 04:41:13 GMT+0000 (Coordinated Universal Time)

RSpec Tip: Keeping Controller Specs DRY

I am not yet converted to the idea of testing/specing views in separation so I usually invoke integrate_views at the top of my controller specs. I also have a bunch of helper methods that I want to reuse across my specs. To encapsulate those needs and DRY up my specs I came up with this little method that I keep in my spec/spec_helper.rb file:

# Describe a controller the way we want to do it for this app, i.e. with
# views integrated and with certain controller spec helper methods available
require File.join(File.dirname(__FILE__), "controller_spec_helper")
def describe_controller(controller, &block)
  describe controller do
    include ControllerSpecHelper
    integrate_views
    block.bind(self).call
  end
end

The controller_spec_helper.rb file looks like this:

module ControllerSpecHelper
  def login_user(username)
    session[:casfilteruser] = username
  end

  def logout
    session[:casfilteruser] = nil
  end

  def get_page(action, options = {})
    get action, options
    response.should be_success
  end  
end