diff --git a/CHANGELOG.md b/CHANGELOG.md index 3fb31d825..f0797ef0a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Master (Unreleased) +- Fix false-positive for `RSpec/UnspecifiedException` when a method is literally named `raise_exception`. ([@aarestad]) + ## 3.0.5 (2024-09-07) - Fix false-negative and error for `RSpec/MetadataStyle` when non-literal args are used in metadata in `EnforceStyle: hash`. ([@cbliard]) @@ -899,6 +901,7 @@ Compatibility release so users can upgrade RuboCop to 0.51.0. No new features. +[@aarestad]: https://github.com/aarestad [@abrom]: https://github.com/abrom [@ahukkanen]: https://github.com/ahukkanen [@akiomik]: https://github.com/akiomik diff --git a/lib/rubocop/cop/rspec/unspecified_exception.rb b/lib/rubocop/cop/rspec/unspecified_exception.rb index ed49701a8..30d4c49af 100644 --- a/lib/rubocop/cop/rspec/unspecified_exception.rb +++ b/lib/rubocop/cop/rspec/unspecified_exception.rb @@ -62,7 +62,10 @@ def empty_exception_matcher?(node) end def find_expect_to(node) - node.each_ancestor(:send).find do |ancestor| + node.each_ancestor.find do |ancestor| + break if ancestor.block_type? + next unless ancestor.send_type? + expect_to?(ancestor) end end diff --git a/spec/rubocop/cop/rspec/unspecified_exception_spec.rb b/spec/rubocop/cop/rspec/unspecified_exception_spec.rb index bb5db00bd..2181b24bb 100644 --- a/spec/rubocop/cop/rspec/unspecified_exception_spec.rb +++ b/spec/rubocop/cop/rspec/unspecified_exception_spec.rb @@ -85,6 +85,30 @@ }.to raise_error(my_exception) RUBY end + + it 'allows a subject function to be named raise_error' do + expect_no_offenses(<<~RUBY) + def raise_exception + raise StandardError + end + + expect { + raise_error + }.to raise_error(StandardError) + RUBY + end + + it 'allows a subject function to be named raise_exception' do + expect_no_offenses(<<~RUBY) + def raise_exception + raise StandardError + end + + expect { + raise_exception + }.to raise_error(StandardError) + RUBY + end end context 'with raise_exception matcher' do @@ -198,5 +222,29 @@ ^^^^^^^^^^^^^^^ Specify the exception being captured RUBY end + + it 'allows a subject function to be named raise_exception' do + expect_no_offenses(<<~RUBY) + def raise_error + raise StandardError + end + + expect { + raise_exception + }.to raise_exception(StandardError) + RUBY + end + + it 'allows a subject function to be named raise_error' do + expect_no_offenses(<<~RUBY) + def raise_error + raise StandardError + end + + expect { + raise_error + }.to raise_exception(StandardError) + RUBY + end end end