3

The controller:

class UsersController < ApplicationController
  def index
    ...
    authorize User
  end
  ...

The policy:

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

The test:

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

The app fails with Pundit::NotAuthorizedError (not allowed to index? this User) as expected. But the test says:

Pundit::NotDefinedError: unable to find policy UserPolicy for User

Am I doing it wrong? Can I make it find the policy?

UPD It must have to do with rails' autoloading. Calling constantize on 'UserPolicy' makes it autoload app/policies/user_policy.rb in case of the app, and doesn't, in case of the tests.

UPD The problem supposedly laid in spring. After stopping it, the tests now output:

Pundit::NotAuthorizedError: not allowed to index? this User
x-yuri
  • 16,722
  • 15
  • 114
  • 161

2 Answers2

7

To fix this issue, I ran:

bin/spring stop
bin/spring binstub --remove --all
bundle update spring
bundle exec spring binstub --all
rylanb
  • 604
  • 6
  • 15
1

In your question, you have:

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

I think that you're missing a question mark:

class UserPolicy < ApplicationPolicy
  def index?                 # <-- Added ? to method name <---
    @user.admin?
  end
end
David Hempy
  • 5,373
  • 2
  • 40
  • 68