ruby-on-rails - pundit rspec - 未初始化的常量 UserPolicy,为什么?
问题描述
寻求帮助,我是 Rspec 和权威人士的菜鸟,我正在按照一个示例来设置权威人士并对其进行测试,但所有测试都失败了
NameError:
uninitialized constant UserPolicy
# ./spec/policies/user_policy_spec.rb:1:in `<top (required)>'
No examples found.
需要一些帮助来弄清楚为什么,因为我不知道:(
使用:
- 导轨 5.1.6
- RSpec 3.7
- rspec 核心 3.7.1
- rspec-expectations 3.7.0
- rspec 模拟 3.7.0
- rspec-rails 3.7.2
- rspec 支持 3.7.1
- 权威 1.1.0
- 设计 4.4.3
配置/初始化程序/pundit.rb
module PunditHelper
extend ActiveSupport::Concern
included do
include Pundit
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
end
private
def user_not_authorized
flash[:alert] = "Access denied."
redirect_to (request.referrer || root_path)
end
end
ApplicationController.send :include, PunditHelper
应用程序/策略/user_policy.rb
class UserPolicy
include ApplicationHelper
attr_reader :current_user, :model
def initialize(current_user, model)
@current_user = current_user
@user = model
end
def index?
is_admin?(@current_user)
end
def show?
is_admin?(@current_user) or @current_user == @user
end
def update?
is_admin?(@current_user) or @current_user == @user
end
def destroy?
is_admin?(@current_user) or @current_user == @user
end
end
规范/支持/pundit.rb
require 'pundit/rspec'
规范/rails_helper.rb
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
abort("The Rails environment is running in production mode!") if
Rails.env.production?
require 'rspec/rails'
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
...
规范/政策/user_policy_spec.rb
describe UserPolicy do
subject { UserPolicy }
let (:current_user) { FactoryBot.build_stubbed :user }
let (:other_user) { FactoryBot.build_stubbed :user }
let (:admin) { FactoryBot.build_stubbed :user, :admin }
permissions :index? do
it "denies access if not an admin" do
expect(user_policy).not_to permit(current_user)
end
it "allows access for an admin" do
expect(user_policy).to permit(admin)
end
end
end
应用程序/控制器/users_controller.rb
class UsersController < ApplicationController
include Pundit
before_action :authenticate_user!
after_action :verify_authorized
def index
@users = User.all
authorize User
end
....
end
解决方案
您在 user_policy_spec 文件中缺少“rails_helper”的要求行
require 'rails_helper'
推荐阅读
- templates - 使用 Deployment Manager 模板配置防火墙和启动脚本时出现问题
- flutter - 如何在 tabBarView 中有状态小部件?
- angular - 页面上多次使用组件时如何从父组件发回数据
- sql - 如何减少存储过程的执行时间?
- javascript - 通过与第一列进行比较来更改第二列的颜色
- ios - 将 JSON 转换为对象时,AlamofireObjectMapper 崩溃
- angular - 如何为 Angular 配置视口插件
- angular - 同步可观测角度
- java - 如何在多模块 Gradle 项目中构建分发包?
- javascript - 如何根据下拉选择代码点火器刷新值