x-y*_*uri 3 ruby testing bdd automated-tests pundit
控制器:
class UsersController < ApplicationController
def index
...
authorize User
end
...
Run Code Online (Sandbox Code Playgroud)
政策:
class UserPolicy < ApplicationPolicy
def index
@user.admin?
end
end
Run Code Online (Sandbox Code Playgroud)
考试:
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
Run Code Online (Sandbox Code Playgroud)
该应用程序Pundit::NotAuthorizedError (not allowed to index? this User)按预期失败.但测试说:
Pundit::NotDefinedError: unable to find policy UserPolicy for User
Run Code Online (Sandbox Code Playgroud)
我做错了吗?我可以让它找到政策吗?
UPD必须与rails'自动加载'有关.调用constantize上'UserPolicy'使得它自动加载app/policies/user_policy.rb的应用程序的情况下,并没有在测试的情况下.
UPD应该提出的问题spring.停止后,测试现在输出:
Pundit::NotAuthorizedError: not allowed to index? this User
Run Code Online (Sandbox Code Playgroud)
为了解决这个问题,我跑了:
bin/spring stop
bin/spring binstub --remove --all
bundle update spring
bundle exec spring binstub --all
Run Code Online (Sandbox Code Playgroud)