From a97b0a11bf6e1a7b3135768d2773315b59b25307 Mon Sep 17 00:00:00 2001 From: Pablo Brasero Date: Thu, 26 May 2022 12:32:31 +0100 Subject: [PATCH] Provide better error messages --- lib/administrate/not_authorized_error.rb | 10 +++- .../administrate/not_authorized_error_spec.rb | 51 +++++++++++++++++++ 2 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 spec/lib/administrate/not_authorized_error_spec.rb diff --git a/lib/administrate/not_authorized_error.rb b/lib/administrate/not_authorized_error.rb index a411fe256b..bc65ab0705 100644 --- a/lib/administrate/not_authorized_error.rb +++ b/lib/administrate/not_authorized_error.rb @@ -4,7 +4,15 @@ def initialize(action:, resource:) @action = action @resource = resource - super("not allowed to #{action.inspect} this #{resource.class}") + case resource + when Module, String, Symbol + super("Not allowed to perform #{action.inspect} on #{resource.inspect}") + else + super( + "Not allowed to perform #{action.inspect} on the given " + + resource.class.name + ) + end end end end diff --git a/spec/lib/administrate/not_authorized_error_spec.rb b/spec/lib/administrate/not_authorized_error_spec.rb new file mode 100644 index 0000000000..b94b11b5fa --- /dev/null +++ b/spec/lib/administrate/not_authorized_error_spec.rb @@ -0,0 +1,51 @@ +require "rails_helper" + +describe Administrate::NotAuthorizedError do + context "when the resource is a class or module" do + it "produces a message mentioning it directly" do + error = described_class.new( + resource: Administrate, + action: "foo", + ) + expect(error.message).to eq( + %{Not allowed to perform "foo" on Administrate} + ) + end + end + + context "when the resource is a string" do + it "produces a message mentioning it directly" do + error = described_class.new( + resource: "User", + action: "foo", + ) + expect(error.message).to eq(%{Not allowed to perform "foo" on "User"}) + end + end + + context "when the resource is a symbol" do + it "produces a message mentioning it directly" do + error = described_class.new( + resource: :user, + action: "foo", + ) + expect(error.message).to eq(%{Not allowed to perform "foo" on :user}) + end + end + + context "when the resource is something else" do + it "produces a message that refers to the class of the resource" do + class TestStuff; end + + error = described_class.new( + resource: TestStuff.new, + action: "foo", + ) + expect(error.message).to eq( + %{Not allowed to perform "foo" on the given TestStuff} + ) + ensure + remove_constants :TestStuff + end + end +end