Skip to content

Commit fb10f1e

Browse files
committed
Improve readability of #check_previous_nodes
1 parent 887a06d commit fb10f1e

File tree

2 files changed

+37
-8
lines changed

2 files changed

+37
-8
lines changed

lib/rubocop/cop/rspec/leading_subject.rb

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -43,20 +43,24 @@ def on_block(node)
4343
end
4444

4545
def check_previous_nodes(node)
46-
node.parent.each_child_node do |sibling|
47-
if offending?(sibling)
48-
msg = format(MSG, offending: sibling.method_name)
49-
add_offense(node, message: msg) do |corrector|
50-
autocorrect(corrector, node, sibling)
51-
end
46+
offending_node(node) do |offender|
47+
msg = format(MSG, offending: offender.method_name)
48+
add_offense(node, message: msg) do |corrector|
49+
autocorrect(corrector, node, offender)
5250
end
53-
54-
break if offending?(sibling) || sibling.equal?(node)
5551
end
5652
end
5753

5854
private
5955

56+
def offending_node(node)
57+
node.parent.each_child_node.find do |sibling|
58+
break if sibling.equal?(node)
59+
60+
yield sibling if offending?(sibling)
61+
end
62+
end
63+
6064
def autocorrect(corrector, node, sibling)
6165
RuboCop::RSpec::Corrector::MoveNode.new(
6266
node, corrector, processed_source

spec/rubocop/cop/rspec/leading_subject_spec.rb

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,4 +135,29 @@
135135
end
136136
RUBY
137137
end
138+
139+
it 'checks also when subject is below a non-offending node' do
140+
expect_offense(<<~RUBY)
141+
RSpec.describe do
142+
def helper_method
143+
end
144+
145+
it { is_expected.to be_present }
146+
147+
subject { described_class.new }
148+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Declare `subject` above any other `it` declarations.
149+
end
150+
RUBY
151+
152+
expect_correction(<<~RUBY)
153+
RSpec.describe do
154+
def helper_method
155+
end
156+
157+
subject { described_class.new }
158+
it { is_expected.to be_present }
159+
160+
end
161+
RUBY
162+
end
138163
end

0 commit comments

Comments
 (0)