Skip to content

Commit fd1bef6

Browse files
authored
Merge pull request #2156 from rubocop/preserve-the-order-or-lets
Preserve the order of declarations when auto-correcting
2 parents 8249b90 + bf1baf3 commit fd1bef6

File tree

3 files changed

+38
-2
lines changed

3 files changed

+38
-2
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
## Master (Unreleased)
44

5+
- `RSpec/ScatteredLet` now preserves the order of `let`s during auto-correction. ([@Darhazer])
56
- Fix a false negative for `RSpec/EmptyLineAfterFinalLet` inside `shared_examples` / `include_examples` / `it_behaves_like` blocks. ([@Darhazer])
67

78
## 3.9.0 (2026-01-07)

lib/rubocop/cop/rspec/scattered_let.rb

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,15 +41,21 @@ def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
4141

4242
def check_let_declarations(body)
4343
lets = body.each_child_node.select { |node| let?(node) }
44+
return if lets.empty?
4445

4546
first_let = lets.first
47+
reference_let = first_let
48+
4649
lets.each_with_index do |node, idx|
47-
next if node.sibling_index == first_let.sibling_index + idx
50+
if node.sibling_index == first_let.sibling_index + idx
51+
reference_let = node
52+
next
53+
end
4854

4955
add_offense(node) do |corrector|
5056
RuboCop::RSpec::Corrector::MoveNode.new(
5157
node, corrector, processed_source
52-
).move_after(first_let)
58+
).move_after(reference_let)
5359
end
5460
end
5561
end

spec/rubocop/cop/rspec/scattered_let_spec.rb

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,4 +158,33 @@
158158
end
159159
RUBY
160160
end
161+
162+
it 'preserves the order of `let`s' do
163+
expect_offense(<<~RUBY)
164+
describe User do
165+
let(:a) { a }
166+
let(:b) { b }
167+
it { expect(subject.foo).to eq(a) }
168+
let(:c) { c }
169+
^^^^^^^^^^^^^ Group all let/let! blocks in the example group together.
170+
let(:d) { d }
171+
^^^^^^^^^^^^^ Group all let/let! blocks in the example group together.
172+
it { expect(subject.bar).to eq(d) }
173+
let(:e) { e }
174+
^^^^^^^^^^^^^ Group all let/let! blocks in the example group together.
175+
end
176+
RUBY
177+
178+
expect_correction(<<~RUBY)
179+
describe User do
180+
let(:a) { a }
181+
let(:b) { b }
182+
let(:c) { c }
183+
let(:d) { d }
184+
let(:e) { e }
185+
it { expect(subject.foo).to eq(a) }
186+
it { expect(subject.bar).to eq(d) }
187+
end
188+
RUBY
189+
end
161190
end

0 commit comments

Comments
 (0)