Skip to content

Commit

Permalink
Merge pull request #1918 from Earlopain/invalid-autocorrect-scattered…
Browse files Browse the repository at this point in the history
…-setup

[Fix #1913] Fix broken autocorrect for `RSpec/ScatteredSetup` when block contains heredoc
  • Loading branch information
Darhazer authored Jun 13, 2024
2 parents e59abf3 + e6106a3 commit 4ee16c9
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 8 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## Master (Unreleased)

- Fix wrong autocorrect for `RSpec/ScatteredSetup` when hook contains heredoc. ([@earlopain])

## 3.0.1 (2024-06-11)

- Bump RuboCop requirement to +1.61. ([@ydah])
Expand Down
8 changes: 7 additions & 1 deletion lib/rubocop/cop/rspec/scattered_setup.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ module RSpec
# end
#
class ScatteredSetup < Base
include FinalEndLocation
include RangeHelp
extend AutoCorrector

Expand Down Expand Up @@ -75,8 +76,13 @@ def message(occurrences, occurrence)
def autocorrect(corrector, first_occurrence, occurrence)
return if first_occurrence == occurrence || !first_occurrence.body

# Take heredocs into account
body = occurrence.body&.source_range&.with(
end_pos: final_end_location(occurrence).begin_pos
)

corrector.insert_after(first_occurrence.body,
"\n#{occurrence.body&.source}")
"\n#{body&.source}")
corrector.remove(range_by_whole_lines(occurrence.source_range,
include_final_newline: true))
end
Expand Down
39 changes: 32 additions & 7 deletions spec/rubocop/cop/rspec/scattered_setup_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
expect_correction(<<~RUBY)
describe Foo do
before { bar
baz }
baz }
end
RUBY
end
Expand All @@ -34,8 +34,8 @@
expect_correction(<<~RUBY)
describe Foo do
after { bar
baz
baz }
baz#{' '}
baz }
end
RUBY
end
Expand All @@ -53,7 +53,7 @@
expect_correction(<<~RUBY)
describe Foo do
before(:all) { bar
baz }
baz }
end
RUBY
end
Expand Down Expand Up @@ -143,9 +143,9 @@
expect_correction(<<~RUBY)
describe Foo do
before(:each, :special_case) { foo
bar
bar
bar }
bar#{' '}
bar#{' '}
bar }
before(:example, special_case: false) { bar }
end
RUBY
Expand All @@ -168,4 +168,29 @@
end
RUBY
end

it 'flags hooks that contain heredoc arguments and autocorrects correctly' do
expect_offense(<<~RUBY)
describe Foo do
before { foo }
^^^^^^^^^^^^^^ Do not define multiple `before` hooks in the same example group (also defined on line 3).
before do
^^^^^^^^^ Do not define multiple `before` hooks in the same example group (also defined on line 2).
bar(<<~'TEXT')
Hello World!
TEXT
end
end
RUBY

expect_correction(<<~RUBY)
describe Foo do
before { foo
bar(<<~'TEXT')
Hello World!
TEXT
}
end
RUBY
end
end

0 comments on commit 4ee16c9

Please sign in to comment.