I was trying to create a function that would check the enforcement of the before filters in my application controller. After going through a lot of rspec documentation and examples, I found nothing that really suited my needs. After a long google, I found a mention in the rspec mailing list and a hint to a solution for this. This is a working example of this idea.
I have in my application controller the following code:
class ApplicationController < ActionController::Base before_filter :check_authorization .... # Checks if a user is authorized def check_authorization User.check_authorization(controller_name, action_name) end end
And in spec/controllers/application/application_spec.rb the following description.
describe "an authorized controller", :shared => true do it "should have the check_authorization set in the before filter" do ApplicationController.before_filters.should \ include(:check_authorization) end end
In all other controller specs I can now do this:
require 'application_controller_spec' describe UnitsController, "in general" do it_should_behave_like "an authorized controller" end
By doing this I now have a spec that ensures that every controller checks authorizations before doing anything else. How cool is that :)!
It would be nicer if the test handled skip before_filters in some nice way like:
it_should_behave_like "a monkey".except_for_action('show')Has anyone got any ideas for that?
Special thanks to Matthijs Langenberg for his insights.