Peter Marklund

Peter Marklund's Home

Mon October 01, 2007
Programming

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

Comments

brian said over 5 years ago:

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>

--------------------------------------------------------------------------------