Skip to content

Commit

Permalink
[Fix rubocop#12668] Fix an incorrect autocorrect for `Lint/EmptyCondi…
Browse files Browse the repository at this point in the history
…tionalBody`

Fixes rubocop#12668.

This PR fixes an incorrect autocorrect for `Lint/EmptyConditionalBody`
when missing `if` body with conditional `else` body.
  • Loading branch information
koic committed Feb 2, 2024
1 parent 3f24b82 commit 5307cec
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
@@ -0,0 +1 @@
* [#12668](https://github.com/rubocop/rubocop/issues/12668): Fix an incorrect autocorrect for `Lint/EmptyConditionalBody` when missing `if` body with conditional `else` body. ([@koic][])
2 changes: 1 addition & 1 deletion lib/rubocop/cop/lint/empty_conditional_body.rb
Expand Up @@ -104,7 +104,7 @@ def remove_empty_branch(corrector, node)
def correct_other_branches(corrector, node)
return unless require_other_branches_correction?(node)

if node.else_branch&.if_type?
if node.else_branch&.if_type? && !node.else_branch.modifier_form?
# Replace an orphaned `elsif` with `if`
corrector.replace(node.else_branch.loc.keyword, 'if')
else
Expand Down
32 changes: 32 additions & 0 deletions spec/rubocop/cop/lint/empty_conditional_body_spec.rb
Expand Up @@ -208,6 +208,38 @@ class Foo
RUBY
end

it 'registers an offense for missing `if` body with conditional `else` body' do
expect_offense(<<~RUBY)
if condition
^^^^^^^^^^^^ Avoid `if` branches without a body.
else
do_something if x
end
RUBY

expect_correction(<<~RUBY)
unless condition
do_something if x
end
RUBY
end

it 'registers an offense for missing `unless` body with conditional `else` body' do
expect_offense(<<~RUBY)
unless condition
^^^^^^^^^^^^^^^^ Avoid `unless` branches without a body.
else
do_something if x
end
RUBY

expect_correction(<<~RUBY)
if condition
do_something if x
end
RUBY
end

it 'registers an offense for missing `unless` and `else` body' do
expect_offense(<<~RUBY)
unless condition
Expand Down

0 comments on commit 5307cec

Please sign in to comment.