Skip to content

Commit

Permalink
refactor: Update proposed change to address feedback from Pundit main…
Browse files Browse the repository at this point in the history
…tainers
  • Loading branch information
Greg Fletcher committed May 8, 2024
1 parent 4ca1e45 commit 86c7251
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 7 deletions.
14 changes: 7 additions & 7 deletions lib/pundit/rspec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
27 changes: 27 additions & 0 deletions spec/policies/post_policy_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 86c7251

Please sign in to comment.