From fefb978b134cce3c18f743a3376c0ffadf5fd07a Mon Sep 17 00:00:00 2001 From: Phil Pirozhkov Date: Thu, 20 Aug 2020 01:49:54 +0300 Subject: [PATCH] Fix subject nesting detection in RSpec/LeadingSubject For the following code: RSpec.describe User do let(:foo) { 'bar' } it_behaves_like 'a good citizen' do subject { described_class.new } end end when `on_block` is triggered for `subject`, `node.parent.each_child_node.to_a` is: [ s(:send, nil, :it_behaves_like, s(:str, "a good citizen")), s(:args), s(:block, s(:send, nil, :subject), s(:args), s(:send, s(:send, nil, :described_class), :new)) ] and autocorrect was putting the subject block above all "offenders" coming before it, including the `it_behaves_like` send node. --- CHANGELOG.md | 1 + lib/rubocop/cop/rspec/leading_subject.rb | 6 +++++- spec/rubocop/cop/rspec/leading_subject_spec.rb | 12 ++++++++++++ 3 files changed, 18 insertions(+), 1 deletion(-) 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