3

控制器:

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'自动加载有关。在应用程序的情况下调用constantizeon'UserPolicy'使其自动加载app/policies/user_policy.rb,而在测试的情况下则不会。

UPD据说问题在于spring. 停止它后,测试现在输出:

Pundit::NotAuthorizedError: not allowed to index? this User
4

2 回答 2

7

为了解决这个问题,我跑了:

bin/spring stop
bin/spring binstub --remove --all
bundle update spring
bundle exec spring binstub --all
于 2016-07-07T03:02:00.480 回答
0

在您的问题中,您有:

class UserPolicy < ApplicationPolicy
  def index
    @user.admin?
  end
end

我认为你错过了一个问号:

class UserPolicy < ApplicationPolicy
  def index?                 # <-- Added ? to method name <---
    @user.admin?
  end
end
于 2018-12-14T19:07:26.640 回答