Peter Marklund

Peter Marklund's Home


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

The controller_spec_helper.rb file looks like this:

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

  def logout
    session[:casfilteruser] = nil

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

1 comment(s)


brian said 2008-12-22 15:05:

this saved me great headaches. I was trying to figure out how to avoid passing the legit session hash to each request method in my spec. after reading your post i realized i could prepare the session in a before filter, like this. <code> before do authenticated_user_session.each_pair do |key,value| session[key] = value end end </code>