diff --git a/CHANGELOG.md b/CHANGELOG.md index a9823231680c..4eb8a8bc67cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ * [#4451](https://github.com/bbatsov/rubocop/issues/4451): Make `Style/AndOr` cop aware of comparison methods. ([@drenmi][]) * [#4457](https://github.com/bbatsov/rubocop/pull/4457): Fix false negative in `Lint/Void` with initialize and setter methods. ([@pocke][]) * [#4418](https://github.com/bbatsov/rubocop/issues/4418): Register an offense in `Style/ConditionalAssignment` when the assignment line is the longest line, and it does not exceed the max line length. ([@rrosenblum][]) +* [#4491](https://github.com/bbatsov/rubocop/issues/4491): Prevent bad auto-correct in `Style/EmptyElse` for nested `if`. ([@pocke][]) ### Changes diff --git a/lib/rubocop/cop/style/empty_else.rb b/lib/rubocop/cop/style/empty_else.rb index c39101560dc7..491dc94dbbca 100644 --- a/lib/rubocop/cop/style/empty_else.rb +++ b/lib/rubocop/cop/style/empty_else.rb @@ -121,6 +121,7 @@ def autocorrect(node) end def base_if_node(node) + return node unless node.case_type? || node.elsif? node.each_ancestor(:if).find { |parent| parent.loc.end } || node end diff --git a/spec/rubocop/cop/style/empty_else_spec.rb b/spec/rubocop/cop/style/empty_else_spec.rb index eb582a50c7fd..96eb374955d4 100644 --- a/spec/rubocop/cop/style/empty_else_spec.rb +++ b/spec/rubocop/cop/style/empty_else_spec.rb @@ -98,6 +98,27 @@ expect_no_offenses('if cond; foo end') end end + + context 'in an if-statement' do + let(:source) { <<-RUBY.strip_indent } + if cond + if cond2 + something + else + end + end + RUBY + let(:corrected_source) { <<-RUBY.strip_indent } + if cond + if cond2 + something + end + end + RUBY + + it_behaves_like 'auto-correct', 'if' + it_behaves_like 'offense registration' + end end context 'given an unless-statement' do