Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix multiple offense detection for Style/For #8809

Merged
merged 1 commit into from Sep 30, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -9,6 +9,7 @@
### Bug fixes

* [#8810](https://github.com/rubocop-hq/rubocop/pull/8810): Fix multiple offense detection for Style/RaiseArgs. ([@pbernays][])
* [#8809](https://github.com/rubocop-hq/rubocop/pull/8809): Fix multiple offense detection for Style/For. ([@pbernays][])

### Changes

Expand Down
4 changes: 0 additions & 4 deletions lib/rubocop/cop/style/for.rb
Expand Up @@ -49,8 +49,6 @@ class For < Base

def on_for(node)
if style == :each
return unless opposite_style_detected

add_offense(node, message: PREFER_EACH) do |corrector|
ForToEachCorrector.new(node).call(corrector)
end
Expand All @@ -63,8 +61,6 @@ def on_block(node)
return unless suspect_enumerable?(node)

if style == :for
return unless opposite_style_detected

add_offense(node, message: PREFER_FOR) do |corrector|
EachToForCorrector.new(node).call(corrector)
end
Expand Down
56 changes: 56 additions & 0 deletions spec/rubocop/cop/style/for_spec.rb
Expand Up @@ -48,6 +48,34 @@ def func
RUBY
end

it 'registers multiple offenses' do
expect_offense(<<~RUBY)
for n in [1, 2, 3] do
^^^^^^^^^^^^^^^^^^^^^ Prefer `each` over `for`.
puts n
end
[1, 2, 3].each do |n|
puts n
end
for n in [1, 2, 3] do
^^^^^^^^^^^^^^^^^^^^^ Prefer `each` over `for`.
puts n
end
RUBY

expect_correction(<<~RUBY)
[1, 2, 3].each do |n|
puts n
end
[1, 2, 3].each do |n|
puts n
end
[1, 2, 3].each do |n|
puts n
end
RUBY
end

context 'auto-correct' do
context 'with range' do
let(:expected_each_with_range) do
Expand Down Expand Up @@ -249,6 +277,34 @@ def func
RUBY
end

it 'registers multiple offenses' do
expect_offense(<<~RUBY)
for n in [1, 2, 3] do
puts n
end
[1, 2, 3].each do |n|
^^^^^^^^^^^^^^^^^^^^^ Prefer `for` over `each`.
puts n
end
[1, 2, 3].each do |n|
^^^^^^^^^^^^^^^^^^^^^ Prefer `for` over `each`.
puts n
end
RUBY

expect_correction(<<~RUBY)
for n in [1, 2, 3] do
puts n
end
for n in [1, 2, 3] do
puts n
end
for n in [1, 2, 3] do
puts n
end
RUBY
end

it 'registers an offense for a tuple of items' do
expect_offense(<<~RUBY)
def func
Expand Down