diff --git a/changelog/fix_an_incorrect_autocorrect_for_lint_empty_conditional_body.md b/changelog/fix_an_incorrect_autocorrect_for_lint_empty_conditional_body.md new file mode 100644 index 000000000000..3020445682d7 --- /dev/null +++ b/changelog/fix_an_incorrect_autocorrect_for_lint_empty_conditional_body.md @@ -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][]) diff --git a/lib/rubocop/cop/lint/empty_conditional_body.rb b/lib/rubocop/cop/lint/empty_conditional_body.rb index 97a7ca078576..39135a59e56a 100644 --- a/lib/rubocop/cop/lint/empty_conditional_body.rb +++ b/lib/rubocop/cop/lint/empty_conditional_body.rb @@ -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 diff --git a/spec/rubocop/cop/lint/empty_conditional_body_spec.rb b/spec/rubocop/cop/lint/empty_conditional_body_spec.rb index 774b182d8a80..12e5c7bd943c 100644 --- a/spec/rubocop/cop/lint/empty_conditional_body_spec.rb +++ b/spec/rubocop/cop/lint/empty_conditional_body_spec.rb @@ -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