From d1c3d90a32cc95115339a3942816107acf6d088c Mon Sep 17 00:00:00 2001 From: Kim Burgestrand Date: Thu, 10 Oct 2024 11:32:57 +0200 Subject: [PATCH] Add a more useful error for when `permissions` is forgotten in rspec --- CHANGELOG.md | 1 + lib/pundit/rspec.rb | 6 +++++- spec/rspec_dsl_spec.rb | 10 ++++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 31eac5fc..674c0417 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ - Deprecated `Pundit::SUFFIX`, moved it to `Pundit::PolicyFinder::SUFFIX` (#835) - Explicitly require less of `active_support` (#837) +- Using `permit` matcher without a surrouding `permissions` block now raises a useful error. (#836) ## 2.4.0 (2024-08-26) diff --git a/lib/pundit/rspec.rb b/lib/pundit/rspec.rb index cafc5913..74c3ed9c 100644 --- a/lib/pundit/rspec.rb +++ b/lib/pundit/rspec.rb @@ -96,7 +96,11 @@ def current_example end def permissions - current_example.metadata[:permissions] + current_example.metadata.fetch(:permissions) do + raise KeyError, <<~ERROR.strip + No permissions in example metadata, did you forget to wrap with `permissions :show?, ...`? + ERROR + end end end # rubocop:enable Metrics/BlockLength diff --git a/spec/rspec_dsl_spec.rb b/spec/rspec_dsl_spec.rb index c1f65dae..45fd6307 100644 --- a/spec/rspec_dsl_spec.rb +++ b/spec/rspec_dsl_spec.rb @@ -36,6 +36,16 @@ end describe "#permit" do + context "when not appropriately wrapped in permissions" do + it "raises a descriptive error" do + expect do + expect(policy).to permit(user, post) + end.to raise_error(KeyError, <<~MSG.strip) + No permissions in example metadata, did you forget to wrap with `permissions :show?, ...`? + MSG + end + end + permissions :edit?, :update? do it "succeeds when action is permitted" do expect(policy).to permit(user, post)