Extend NotAuthorizedError with policy, record and query #117

Closed
wants to merge 4 commits into
from
View
@@ -5,7 +5,9 @@
require "active_support/core_ext/object/blank"
module Pundit
- class NotAuthorizedError < StandardError; end
+ class NotAuthorizedError < StandardError
+ attr_accessor :policy, :record, :query
+ end
class NotDefinedError < StandardError; end
extend ActiveSupport::Concern
@@ -56,7 +58,9 @@ def authorize(record, query=nil)
query ||= params[:action].to_s + "?"
@_policy_authorized = true
unless policy(record).public_send(query)
- raise NotAuthorizedError, "not allowed to #{query} this #{record}"
+ e = NotAuthorizedError.new
+ e.policy, e.record, e.query = policy(record), record, query
+ raise e, "not allowed to #{query} this #{record}"
end
true
end
View
@@ -224,6 +224,15 @@ def destroy?
it "raises an error when the permission check fails" do
expect { controller.authorize(Post.new) }.to raise_error(Pundit::NotAuthorizedError)
end
+
+ it "raises an error with a policy, record and query" do
+ expect { controller.authorize(post, :destroy?) }.to raise_error do |error|
+ expect(error.policy).to eq controller.policy(post)
+ expect(error.record).to eq post
+ expect(error.query).to eq :destroy?
+ expect(error.message).to eq "not allowed to #{error.query} this #{error.record}"
+ end
+ end
end
describe "#pundit_user" do