From a59315fb180454a4fdbf245eebac843a11952c98 Mon Sep 17 00:00:00 2001 From: Peter Aarestad Date: Tue, 13 Aug 2024 14:17:52 -0500 Subject: [PATCH] fix false positive on UnspecifiedException cop when function is named raise_exception --- CHANGELOG.md | 3 ++ .../cop/rspec/unspecified_exception.rb | 5 +- .../cop/rspec/unspecified_exception_spec.rb | 48 +++++++++++++++++++ 3 files changed, 55 insertions(+), 1 deletion(-) 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