Skip to content

Commit c09b42c

Browse files
author
Stanislav (Stas) Katkov
committed
Don't allow to redefine attributes with chaining in with_context method
1 parent 569fa0e commit c09b42c

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

lib/rspec/rails/matchers/have_reported_error.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,12 @@ def initialize(expected_error_or_message, expected_message)
3434
end
3535

3636
def with_context(expected_attributes)
37+
conflicting_keys = @attributes.keys & expected_attributes.keys
38+
unless conflicting_keys.empty?
39+
raise ArgumentError, "Attribute keys #{conflicting_keys.inspect} are already defined. " \
40+
"Chaining with_context calls should not overwrite existing attributes. " \
41+
"Use a single with_context call with all attributes instead."
42+
end
3743
@attributes.merge!(expected_attributes)
3844
self
3945
end

spec/rspec/rails/matchers/have_reported_error_spec.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,20 @@ class AnotherTestError < StandardError; end
163163
expect { "no error" }.to have_reported_error.with_context(user_id: 123)
164164
}.to fail_with(/Expected the block to report an error, but none was reported./)
165165
end
166+
167+
describe "chaining with_context calls" do
168+
it "accumulates attributes when different keys are used in chained calls" do
169+
expect {
170+
Rails.error.report(StandardError.new("test"), context: { user_id: 123, session_id: "abc123", role: "admin" })
171+
}.to have_reported_error.with_context(user_id: 123).with_context(session_id: "abc123")
172+
end
173+
174+
it "raises error when trying to overwrite existing attribute keys" do
175+
expect {
176+
have_reported_error.with_context(user_id: 123).with_context(user_id: 456)
177+
}.to raise_error(ArgumentError, /Attribute keys \[:user_id\] are already defined/)
178+
end
179+
end
166180
end
167181

168182
context "constrained by message only" do

0 commit comments

Comments
 (0)