【问题标题】:Why pundit can't find policies in controller tests?为什么权威人士在控制器测试中找不到策略?
【发布时间】: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


    【解决方案1】:

    为了解决这个问题,我运行了:

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

    【讨论】:

    • 谢谢,Rails 5.0.2 仅运行 API 为我节省了很多时间。
    • 很高兴听到这个消息!
    • 也为我工作。谢谢。想不通,为什么会这样?
    • 我不确定!但是考虑到与 spring 相关的错误,我在遇到相同问题时尝试了它,它清除了需要重新启动的东西。
    【解决方案2】:

    在你的问题中,你有:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多