diff --git a/Changelog.md b/Changelog.md index bc0b7dd6c..23fd1cda0 100644 --- a/Changelog.md +++ b/Changelog.md @@ -5,6 +5,7 @@ Bug Fixes: * When using null object doubles, prevent typos triggering dynamic matchers. (Eric Mueller, #1455) +* Use `RSpec.warning` for an expectation warning rather than `Kernel.warn`. (Jon Rowe, #1472) ### 3.13.1 / 2024-06-13 [Full Changelog](http://github.com/rspec/rspec-expectations/compare/v3.13.0...v3.13.1) diff --git a/lib/rspec/expectations/handler.rb b/lib/rspec/expectations/handler.rb index a8f7c0531..d86061a15 100644 --- a/lib/rspec/expectations/handler.rb +++ b/lib/rspec/expectations/handler.rb @@ -4,11 +4,10 @@ module Expectations module ExpectationHelper def self.check_message(msg) unless msg.nil? || msg.respond_to?(:to_str) || msg.respond_to?(:call) - ::Kernel.warn [ - "WARNING: ignoring the provided expectation message argument (", - msg.inspect, - ") since it is not a string or a proc." - ].join + RSpec.warning( + "ignoring the provided expectation message argument" \ + "(#{ msg.inspect }) since it is not a string or a proc" + ) end end diff --git a/spec/rspec/expectations/handler_spec.rb b/spec/rspec/expectations/handler_spec.rb index 24be7a086..a6695517c 100644 --- a/spec/rspec/expectations/handler_spec.rb +++ b/spec/rspec/expectations/handler_spec.rb @@ -145,6 +145,16 @@ module Expectations expect(handle_matcher_result.error_generator.opts).to eq({ :message => "custom" }) end + + it 'warns when the expectation message is not a string or proc' do + matcher = double("matcher", :matches? => true) + actual = Object.new + not_a_string_or_proc = Object.new + + expect(capture_warnings { + RSpec::Expectations::PositiveExpectationHandler.handle_matcher(actual, matcher, not_a_string_or_proc) + }).to contain_exactly(a_string_matching(/since it is not a string or a proc/)) + end end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 595fafa2c..c0151328d 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -25,6 +25,20 @@ def dedent(string) string.gsub(/^\s+\|/, '').chomp end + def capture_warnings(&block) + warning_notifier = RSpec::Support.warning_notifier + warnings = [] + RSpec::Support.warning_notifier = lambda { |warning| warnings << warning } + + begin + block.call + ensure + RSpec::Support.warning_notifier = warning_notifier + end + + warnings + end + # We have to use Hash#inspect in examples that have multi-entry # hashes because the #inspect output on 1.8.7 is non-deterministic # due to the fact that hashes are not ordered. So we can't simply