diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f868e939..575fef317 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ * Add `RSpec/RepeatedIncludeExample` cop. ([@biinari][]) * Fix `RSpec/FilePath` when checking a file with a shared example. ([@pirj][]) +* Fix subject nesting detection in `RSpec/LeadingSubject`. ([@pirj][]) ## 1.43.1 (2020-08-17) diff --git a/lib/rubocop/cop/rspec/leading_subject.rb b/lib/rubocop/cop/rspec/leading_subject.rb index 1789c55b7..16ece6d24 100644 --- a/lib/rubocop/cop/rspec/leading_subject.rb +++ b/lib/rubocop/cop/rspec/leading_subject.rb @@ -54,13 +54,17 @@ def check_previous_nodes(node) private def offending_node(node) - node.parent.each_child_node.find do |sibling| + parent(node).each_child_node.find do |sibling| break if sibling.equal?(node) yield sibling if offending?(sibling) end end + def parent(node) + node.each_ancestor(:block).first.body + end + def autocorrect(corrector, node, sibling) RuboCop::RSpec::Corrector::MoveNode.new( node, corrector, processed_source diff --git a/spec/rubocop/cop/rspec/leading_subject_spec.rb b/spec/rubocop/cop/rspec/leading_subject_spec.rb index 9bc7d6982..c359bc2d0 100644 --- a/spec/rubocop/cop/rspec/leading_subject_spec.rb +++ b/spec/rubocop/cop/rspec/leading_subject_spec.rb @@ -269,4 +269,16 @@ def helper_method end RUBY end + + it 'ignores subject nested inside a block' do + expect_no_offenses(<<-RUBY) + RSpec.describe User do + let(:foo) { 'bar' } + + it_behaves_like 'a good citizen' do + subject { described_class.new } + end + end + RUBY + end end