Question

The simplest way to write specs checking that a controller is authorizing the signed-in current_user to use the said action is to explicitly write two specs checking that a user with permission can run that action, and another cannot. For example:

 # The controller action:

 def some_action
   authorize! :do_this_action, @some_object
 end

 # The spec:

 it "should work when authorized" do
   sign_in @user
   get :some_action
   response.should be_success
 end

 it "should not work when not authorized" do
   sign_in @other_user
   get :some_action
   response.should_not be_success
 end

But this is not great, as it requires a great amount of code (two or more specs) and doesn't actually test directly that the authorization is being checked (do_this_action in the example).

I would like to be able to write a simpler spec, e.g. (an example using 'rr' for mocking)

 it "should check the user can do_this_action" do
   mock(controller).authorize!(:do_this_action, some_object)
   get :some_action
 end

I think this would be shorter and directly test that the authorization check I want to be used is being run. But, I can't figure out how to write the mock. mock(controller) isn't correct, nor does mocking ApplicationController or Ability seem to work.

How do I write this kind of mock?

Was it helpful?

Solution 2

It turns out the way I was writing above works.. must have had a typo earlier.

So, to check that an authorize! check is invoked in the controller, you just need to write:

 it "should check the user can do_this_action" do
   mock(controller).authorize!(:some_action, some_object)
   get :some_action
 end

OTHER TIPS

I believe it would be better to test authorization in another spec like ability_spec.rb in order for you to separate their responsibilities. By doing so you won't have to test the same authorization method that you use on different controllers.

heres some other details

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top