Pundit - 授权不被调用,但没有错误被抛出

Pundit - authorize not being called, but no error is being thrown

我正在使用专家进行授权。它没有按预期工作,但是在调用 authorize 时没有抛出错误说没有方法。

规格:

it "should let a user destroy their own picture" do
  sign_in(user2)
  expect do
    delete :destroy, { id: p1.id }
    expect(response.status).to eq(200)
  end.to change { Picture.count }.by(-1)
end

it "should not let a user delete another user's picture" do
  sign_in(user2)
  expect do
    delete :destroy, { id: p1.id }
    expect(response.status).to eq(403)
  end.to change { Picture.count }.by(0)
end

应用程序控制器:

class ApplicationController < ActionController::Base
  ...
  include Pundit
  rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
  ...
end

图片控制器:

class PicturesController < ApplicationController
  def destroy
    @picture = Picture.find_by_id(params[:id])
    authorize(@picture)
    @picture.destroy
    redirect_to pictures_path
  end
end

应用策略

class ApplicationPolicy
  attr_reader :user, :record

  def initialize(user, record)
    @user = user
    @record = record
  end

  def scope
    Pundit.policy_scope!(user, record.class)
  end

  class Scope
    attr_reader :user, :scope

    def initialize(user, scope)
      @user = user
      @scope = scope
    end

    def resolve
      scope
    end
  end
end

图片策略

class PicturePolicy < ApplicationPolicy
  def destroy?
    @user&.id == @record&.user_id
  end
end

当我 运行 我用 authorize(picture) 行测试时,两者都没有被破坏,没有它,两个都被破坏。在 PicturePolicy#destroy? 中添加一些 put 语句时,它们不会显示。如果我添加一个ApplicationPolicy#destroy?,它似乎也没有被调用。但是,当我将 authorize(obj) 添加到我的控制器时,该代码之后没有任何内容 运行,策略#authorize 都没有 运行,但返回了 200。

知道我在这里遗漏了什么吗?

发现问题。我在 ruby 的版本中使用安全访问 &. 它不存在。删除它修复了它。