diff --git a/changelog/fix_an_incorrect_autocorrect_for_rails_strong_parameters_expect.md b/changelog/fix_an_incorrect_autocorrect_for_rails_strong_parameters_expect.md new file mode 100644 index 0000000000..426ad18c94 --- /dev/null +++ b/changelog/fix_an_incorrect_autocorrect_for_rails_strong_parameters_expect.md @@ -0,0 +1 @@ +* [#1417](https://github.com/rubocop/rubocop-rails/issues/1417): Fix an incorrect autocorrect for `Rails/StrongParametersExpect` when using a leading dot multiline call to `require` with `permit`. ([@koic][]) diff --git a/lib/rubocop/cop/rails/strong_parameters_expect.rb b/lib/rubocop/cop/rails/strong_parameters_expect.rb index 842523f629..54b108ab6a 100644 --- a/lib/rubocop/cop/rails/strong_parameters_expect.rb +++ b/lib/rubocop/cop/rails/strong_parameters_expect.rb @@ -59,7 +59,7 @@ def on_send(node) end add_offense(range, message: format(MSG, prefer: prefer)) do |corrector| - corrector.remove(require_method.loc.dot.join(require_method.source_range.end)) + corrector.remove(require_method.receiver.source_range.end.join(require_method.source_range.end)) corrector.replace(permit_method.loc.selector, 'expect') if replace_argument corrector.insert_before(permit_method.first_argument, "#{require_key(require_method)}[") diff --git a/spec/rubocop/cop/rails/strong_parameters_expect_spec.rb b/spec/rubocop/cop/rails/strong_parameters_expect_spec.rb index 036822f9ea..f7758327ca 100644 --- a/spec/rubocop/cop/rails/strong_parameters_expect_spec.rb +++ b/spec/rubocop/cop/rails/strong_parameters_expect_spec.rb @@ -98,6 +98,20 @@ RUBY end + it 'registers an offense when using a leading dot multiline call to `params.require(:user).permit(:name, :age)`' do + expect_offense(<<~RUBY) + params + .require(:user) + ^^^^^^^^^^^^^^ Use `expect(user: [:name, :age])` instead. + .permit(:name, :age) + RUBY + + expect_correction(<<~RUBY) + params + .expect(user: [:name, :age]) + RUBY + end + it 'does not register an offense when using `params.expect(user: [:name, :age])`' do expect_no_offenses(<<~RUBY) params.expect(user: [:name, :age])