From 853575dff6407d187264c17a45f1d900eb9b0005 Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Tue, 9 Feb 2021 09:22:23 +0900 Subject: [PATCH] [Fix #435] Fix a false negative for `Rails/BelongsTo` Fixes #435. This PR fixes a false negative for `Rails/BelongsTo` when using `belongs_to` lambda block with `required: false`. --- CHANGELOG.md | 4 ++++ lib/rubocop/cop/rails/belongs_to.rb | 2 +- spec/rubocop/cop/rails/belongs_to_spec.rb | 11 +++++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fbc4139bc3..20b7b65961 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Change log +### Bug fixes + +* [#435](https://github.com/rubocop-hq/rubocop-rails/issues/435): Fix a false negative for `Rails/BelongsTo` when using `belongs_to` lambda block with `required: false`. ([@koic][]) + ## master (unreleased) ### Bug fixes diff --git a/lib/rubocop/cop/rails/belongs_to.rb b/lib/rubocop/cop/rails/belongs_to.rb index 807214074c..e6cb7ac06e 100644 --- a/lib/rubocop/cop/rails/belongs_to.rb +++ b/lib/rubocop/cop/rails/belongs_to.rb @@ -68,7 +68,7 @@ class BelongsTo < Base RESTRICT_ON_SEND = %i[belongs_to].freeze def_node_matcher :match_belongs_to_with_options, <<~PATTERN - (send _ :belongs_to _ + (send _ :belongs_to ... (hash <$(pair (sym :required) ${true false}) ...>) ) PATTERN diff --git a/spec/rubocop/cop/rails/belongs_to_spec.rb b/spec/rubocop/cop/rails/belongs_to_spec.rb index bbbeffc2c8..c377d920b0 100644 --- a/spec/rubocop/cop/rails/belongs_to_spec.rb +++ b/spec/rubocop/cop/rails/belongs_to_spec.rb @@ -23,6 +23,17 @@ RUBY end + it 'registers an offense and corrects when using `belongs_to` lambda block with `required: false`' do + expect_offense(<<~RUBY) + belongs_to :foo, -> { bar }, required: false + ^^^^^^^^^^ You specified `required: false`, in Rails > 5.0 the required option is deprecated and you want to use `optional: true`. + RUBY + + expect_correction(<<~RUBY) + belongs_to :foo, -> { bar }, optional: true + RUBY + end + it 'registers no offense when setting `optional: true`' do expect_no_offenses('belongs_to :foo, optional: true') end