gpt4 book ai didi

ruby-on-rails - pundit rspec - 未初始化的常量 UserPolicy,为什么?

转载 作者:行者123 更新时间:2023-12-03 09:00:23 24 4
gpt4 key购买 nike

寻求一些帮助,我对 Rspec 和 pundit 是个菜鸟,我正在按照一个示例来设置 pundit 并对其进行测试,但所有测试都失败了

NameError:
uninitialized constant UserPolicy
# ./spec/policies/user_policy_spec.rb:1:in `<top (required)>'
No examples found.

需要一些帮助来找出原因,因为我不知道:(

使用:

  • Rails 5.1.6
  • RSpec 3.7
    • rspec-core 3.7.1
    • rspec-期望 3.7.0
    • rspec-mocks 3.7.0
    • rspec-rails 3.7.2
    • rspec-支持 3.7.1
  • 专家1.1.0
  • 设计4.4.3

config/initializers/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

app/policies/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

spec/support/pundit.rb

require 'pundit/rspec'

spec/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 }
...

spec/policies/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

app/controllers/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”

关于ruby-on-rails - pundit rspec - 未初始化的常量 UserPolicy,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51018559/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com