diff --git a/changelog/fix_incorrect_autocorrect_for_style_and_or.md b/changelog/fix_incorrect_autocorrect_for_style_and_or.md new file mode 100644 index 00000000000..ebf7104233e --- /dev/null +++ b/changelog/fix_incorrect_autocorrect_for_style_and_or.md @@ -0,0 +1 @@ +* [#9646](https://github.com/rubocop/rubocop/pull/9646): Fix an incorrect auto-correct for `EnforcedStyle: require_parentheses` of `Style/MethodCallWithArgsParentheses` with `EnforcedStyle: conditionals` of `Style/AndOr`. ([@koic][]) diff --git a/lib/rubocop/cop/style/and_or.rb b/lib/rubocop/cop/style/and_or.rb index 52c349b0780..9cdc6ebd21c 100644 --- a/lib/rubocop/cop/style/and_or.rb +++ b/lib/rubocop/cop/style/and_or.rb @@ -94,7 +94,9 @@ def correct_send(node, corrector) return unless correctable_send?(node) - corrector.replace(whitespace_before_arg(node), '(') + whitespace_before_arg_range = whitespace_before_arg(node) + corrector.remove(whitespace_before_arg_range) + corrector.insert_before(whitespace_before_arg_range, '(') corrector.insert_after(node.last_argument, ')') end diff --git a/spec/rubocop/cli/autocorrect_spec.rb b/spec/rubocop/cli/autocorrect_spec.rb index cf864d8b8f6..4b66eb090ee 100644 --- a/spec/rubocop/cli/autocorrect_spec.rb +++ b/spec/rubocop/cli/autocorrect_spec.rb @@ -215,6 +215,27 @@ def batch RUBY end + it 'corrects `EnforcedStyle: require_parentheses` of `Style/MethodCallWithArgsParentheses` with ' \ + '`EnforcedStyle: conditionals` of `Style/AndOr`' do + create_file('.rubocop.yml', <<~YAML) + Style/MethodCallWithArgsParentheses: + EnforcedStyle: require_parentheses + Style/AndOr: + EnforcedStyle: conditionals + YAML + create_file('example.rb', <<~RUBY) + if foo and bar :arg + end + RUBY + expect( + cli.run(['--auto-correct', '--only', 'Style/MethodCallWithArgsParentheses,Style/AndOr']) + ).to eq(0) + expect(IO.read('example.rb')).to eq(<<~RUBY) + if foo && bar(:arg) + end + RUBY + end + it 'corrects `Style/IfUnlessModifier` with `Style/SoleNestedConditional`' do source = <<~RUBY def foo