diff --git a/CHANGELOG.md b/CHANGELOG.md index 47e4b611b0b..ed9cc56ac5c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ * [#6648](https://github.com/rubocop-hq/rubocop/issues/6648): Fix auto-correction of `Style/EmptyLiteral` when `Hash.new` is passed as the first argument to `super`. ([@rrosenblum][]) * [#6351](https://github.com/rubocop-hq/rubocop/pull/6351): Fix a false positive for `Layout/ClosingParenthesisIndentation` when first argument is multiline. ([@antonzaytsev][]) * [#6689](https://github.com/rubocop-hq/rubocop/pull/6689): Support more complex argument patterns on `Rails/Validation` auto-correction. ([@r7kamura][]) +* [#6668](https://github.com/rubocop-hq/rubocop/issues/6668): Fix autocorrection for `Style/UnneededCondition` when conditional has the `unless` form. ([@mvz][]) ## 0.63.1 (2019-01-22) diff --git a/lib/rubocop/cop/style/unneeded_condition.rb b/lib/rubocop/cop/style/unneeded_condition.rb index cf51d2d3351..42db20a5b45 100644 --- a/lib/rubocop/cop/style/unneeded_condition.rb +++ b/lib/rubocop/cop/style/unneeded_condition.rb @@ -96,8 +96,9 @@ def else_source(else_branch) end def make_ternary_form(node) - ternary_form = [node.if_branch.source, - else_source(node.else_branch)].join(' || ') + _condition, if_branch, else_branch = *node + ternary_form = [if_branch.source, + else_source(else_branch)].join(' || ') if node.parent && node.parent.send_type? "(#{ternary_form})" diff --git a/spec/rubocop/cop/style/unneeded_condition_spec.rb b/spec/rubocop/cop/style/unneeded_condition_spec.rb index faa6d5fe320..6fc5af124de 100644 --- a/spec/rubocop/cop/style/unneeded_condition_spec.rb +++ b/spec/rubocop/cop/style/unneeded_condition_spec.rb @@ -225,4 +225,57 @@ end end end + + context 'when inverted condition (unless)' do + it 'registers no offense' do + expect_no_offenses(<<-RUBY.strip_indent) + unless a + b + else + c + end + RUBY + end + + context 'when condition and else branch are same' do + it 'registers an offense' do + expect_offense(<<-RUBY.strip_indent) + unless b + ^^^^^^^^ Use double pipes `||` instead. + y(x, z) + else + b + end + RUBY + end + + context 'when unless branch is complex' do + it 'registers no offense' do + expect_no_offenses(<<-RUBY.strip_indent) + unless b + c + d + else + b + end + RUBY + end + end + end + + describe '#autocorrection' do + it 'auto-corrects offense' do + new_source = autocorrect_source(<<-RUBY.strip_indent) + unless b + c + else + b + end + RUBY + expect(new_source).to eq(<<-RUBY.strip_indent) + b || c + RUBY + end + end + end end