为什么专家在控制器测试中找不到策略?

时间:2015-03-27 10:14:44

标签: ruby testing automated-tests bdd pundit

控制器:

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&#39;自动加载。在'UserPolicy'上拨打constantize可以在应用的情况下自动加载app/policies/user_policy.rb,在测试的情况下不会自动加载spring

UPD 问题应该放在Pundit::NotAuthorizedError: not allowed to index? this User 中。停止后,测试现在输出:

{{1}}

2 个答案:

答案 0 :(得分:7)

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

bin/spring stop
bin/spring binstub --remove --all
bundle update spring
bundle exec spring binstub --all

答案 1 :(得分:0)

您的问题中,您有:

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

我认为您缺少问号:

class UserPolicy < ApplicationPolicy
  def index?                 # <-- Added ? to method name <---
    @user.admin?
  end
end