控制器:
class UsersController < ApplicationController
def index
...
authorize User
end
...
政策:
class UserPolicy < ApplicationPolicy
def index
@user.admin?
end
end
考试:
class UsersControllerAuthorizationTest < ActionController::TestCase
tests :users
def user
@user ||= create(:user)
end
test 'should not authorize ordinary users to access the page' do
sign_in user
get :index
assert_response :error
end
end
Pundit::NotAuthorizedError (not allowed to index? this User)
该应用程序按预期失败。但是测试说:
Pundit::NotDefinedError: unable to find policy UserPolicy for User
我做错了吗?我可以让它找到政策吗?
UPD它必须与rails
'自动加载有关。在应用程序的情况下调用constantize
on'UserPolicy'
使其自动加载app/policies/user_policy.rb
,而在测试的情况下则不会。
UPD据说问题在于spring
. 停止它后,测试现在输出:
Pundit::NotAuthorizedError: not allowed to index? this User