Skip to content

Commit

Permalink
[Fix rubocop#435] Fix a false negative for Rails/BelongsTo
Browse files Browse the repository at this point in the history
Fixes rubocop#435.

This PR fixes a false negative for `Rails/BelongsTo`
when using `belongs_to` lambda block with `required: false`.
  • Loading branch information
koic committed Feb 9, 2021
1 parent d6868a6 commit 853575d
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
2 changes: 1 addition & 1 deletion lib/rubocop/cop/rails/belongs_to.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions spec/rubocop/cop/rails/belongs_to_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 853575d

Please sign in to comment.