From 86c72511c21cdf9b8b97bb2a314b3d8f97248aa4 Mon Sep 17 00:00:00 2001 From: Greg Fletcher Date: Wed, 8 May 2024 18:24:10 -0400 Subject: [PATCH] refactor: Update proposed change to address feedback from Pundit maintainers --- lib/pundit/rspec.rb | 14 +++++++------- spec/policies/post_policy_spec.rb | 27 +++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 7 deletions(-) diff --git a/lib/pundit/rspec.rb b/lib/pundit/rspec.rb index c88407d2..5becb308 100644 --- a/lib/pundit/rspec.rb +++ b/lib/pundit/rspec.rb @@ -5,14 +5,14 @@ module RSpec module Matchers extend ::RSpec::Matchers::DSL - def self.default_description=(default_description) - @default_description = default_description - end + class << self + attr_writer :description - def self.default_description - return @default_description if instance_variable_defined?(:@default_description) + def description(user, record) + return @description.call(user, record) if defined?(@description) && @description.respond_to?(:call) - nil + @description + end end # rubocop:disable Metrics/BlockLength @@ -44,7 +44,7 @@ def self.default_description end description do - Pundit::RSpec::Matchers.default_description || super() + Pundit::RSpec::Matchers.description(user, record) || super() end if respond_to?(:match_when_negated) diff --git a/spec/policies/post_policy_spec.rb b/spec/policies/post_policy_spec.rb index 54e301e0..912fe74b 100644 --- a/spec/policies/post_policy_spec.rb +++ b/spec/policies/post_policy_spec.rb @@ -18,5 +18,32 @@ should permit(user, other_post) end.to raise_error(RSpec::Expectations::ExpectationNotMetError) end + + it "uses the default description if not overridden" do + expect(permit(user, own_post).description).to eq("permit #{user.inspect} and #{own_post.inspect}") + end + + context "when the matcher description is overridden" do + after do + Pundit::RSpec::Matchers.description = nil + end + + it "sets a custom matcher description with a Proc" do + allow(user).to receive(:role).and_return("default_role") + allow(own_post).to receive(:id).and_return(1) + + Pundit::RSpec::Matchers.description = lambda { |user, record| + "permit user with role #{user.role} to access record with ID #{record.id}" + } + + description = permit(user, own_post).description + expect(description).to eq("permit user with role default_role to access record with ID 1") + end + + it "sets a custom matcher description with a string" do + Pundit::RSpec::Matchers.description = "permit user" + expect(permit(user, own_post).description).to eq("permit user") + end + end end end