【发布时间】:2015-03-27 10:14:44
【问题描述】:
控制器:
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'自动加载有关。在 'UserPolicy' 上调用 constantize 使其在应用程序的情况下自动加载 app/policies/user_policy.rb,而在测试的情况下则不会。
UPD 问题应该出在spring。停止它后,测试现在输出:
Pundit::NotAuthorizedError: not allowed to index? this User
【问题讨论】:
标签: ruby testing automated-tests bdd pundit