首页 > 解决方案 > Pundit 工作正常,但为未经授权的用户返回 200 而不是 401

问题描述

我有这样的规格:

it "should let a user destroy their own picture" do
  expect do
    delete :destroy, { id: p1.id }
    puts "\n\nOK resp\n#{response.status}\n\n\n"
  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 }
    puts "\n\nNOT OK resp\n#{response.status}\n\n\n"
  end.to change { Picture.count }.by(0)
end

第一个正确返回一个302(我在销毁后重定向)。第二个正确通过,这意味着用户不能销毁,但它返回一个200状态码,而不是401它应该返回的状态码。

在我的ApplicationController

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

  def user_not_authorized
    render file: "public/401.html", status: :unauthorized
  end
  ...
end

不管有没有这rescue from条线,我仍然得到一个200. 似乎 whilepundit正确地捕获truefalseauthorize(@obj)方法中并停止执行,但是当它得到false.

我怎样才能解决这个问题?

标签: ruby-on-railspundit

解决方案


推荐阅读