From 5723158e40724bab2978007f9fad2bdef5724a65 Mon Sep 17 00:00:00 2001 From: Phil Pirozhkov Date: Sat, 22 Aug 2020 00:59:31 +0300 Subject: [PATCH] Merge pull request #1011 from rubocop-hq/fix-leading-subject Fix subject nesting detection in RSpec/LeadingSubject --- 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 bb77181d3..7f91bfa51 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## Master (Unreleased) * 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