From 6c171edf0beaf52318303807b80d6668c9d66e00 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 | 4 ++++ lib/pundit/rspec.rb | 6 +++++- spec/rspec_dsl_spec.rb | 10 ++++++++++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b16cddbc..fceb6dbc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +### Changed + +- Using `permit` matcher without a surrouding `permissions` block now raises a useful error. (#834) + ## 2.4.0 (2024-08-26) ## Changed diff --git a/lib/pundit/rspec.rb b/lib/pundit/rspec.rb index fb44ba60..192d5c8d 100644 --- a/lib/pundit/rspec.rb +++ b/lib/pundit/rspec.rb @@ -93,7 +93,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)