我正在使用专家进行授权。它没有按预期方式工作,但是在调用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
ApplicationController:
class ApplicationController < ActionController::Base
...
include Pundit
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
...
end
PicturesController:
class PicturesController < ApplicationController
def destroy
@picture = Picture.find_by_id(params[:id])
authorize(@picture)
@picture.destroy
redirect_to pictures_path
end
end
ApplicationPolicy
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
PicturePolicy
class PicturePolicy < ApplicationPolicy
def destroy?
@user&.id == @record&.user_id
end
end
当我使用authorize(picture)
行运行测试时,没有一个被销毁,没有它,两个都被销毁。在PicturePolicy#destroy?
内添加一些put语句时,它们不会显示。如果我添加一个ApplicationPolicy#destroy?
,它似乎也没有被调用。但是,当我在控制器中添加authorize(obj)
时,该代码之后没有执行任何操作,既没有运行policy#authorize,也没有返回200。
知道我在这里缺少什么吗?
答案 0 :(得分:0)
发现了问题。我在一个不存在的ruby版本中使用了安全访问权限&.
。将其修复即可。