[英]How to mock CanCan's “authorize!” method in a controller spec?
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. 编写规范检查以确认控制器正在授权登录的current_user使用所述操作的最简单方法是显式编写两个规范检查,以确保具有许可权的用户可以运行该操作,而另一个则不能。 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). 但这不是很好,因为它需要大量代码(两个或更多规范),并且实际上并没有直接测试是否正在检查授权(在示例中为do_this_action
)。
I would like to be able to write a simpler spec, eg (an example using 'rr' for mocking) 我希望能够编写一个更简单的规范,例如(使用'rr'进行模拟的示例)
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. mock(controller)
不正确, mock(controller)
ApplicationController
或Ability
似乎也不起作用。
How do I write this kind of mock? 我该如何编写这种模拟?
I believe it would be better to test authorization in another spec like ability_spec.rb in order for you to separate their responsibilities. 我认为最好在另一个规范中测试能力,例如capability_spec.rb,以便您区分其职责。 By doing so you won't have to test the same authorization method that you use on different controllers. 这样,您将不必测试在不同控制器上使用的相同授权方法。
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: 在控制器中调用check,您只需要编写:
it "should check the user can do_this_action" do
mock(controller).authorize!(:some_action, some_object)
get :some_action
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.