Skip to content

Commit

Permalink
[Fix rubocop#1105] Fix false positives for `Rails/RedundantPresenceVa…
Browse files Browse the repository at this point in the history
…lidationOnBelongsTo`

Fixes rubocop#1105.

This PR fixes false positives for `Rails/RedundantPresenceValidationOnBelongsTo`
when using `validates` with `:if` or `:unless` options.
  • Loading branch information
koic committed Oct 5, 2023
1 parent b1ff70b commit 1d33f84
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#1105](https://github.com/rubocop/rubocop-rails/issues/1105): Fix false positives for `Rails/RedundantPresenceValidationOnBelongsTo` when using `validates` with `:if` or `:unless` options. ([@koic][])
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,12 @@ class RedundantPresenceValidationOnBelongsTo < Base
# @example source that matches - by a foreign key
# validates :user_id, presence: true
#
# @example source that DOES NOT match - if condition
# validates :user_id, presence: true, if: condition
#
# @example source that DOES NOT match - unless condition
# validates :user_id, presence: true, unless: condition
#
# @example source that DOES NOT match - strict validation
# validates :user_id, presence: true, strict: true
#
Expand All @@ -65,6 +71,7 @@ class RedundantPresenceValidationOnBelongsTo < Base
$[
(hash <$(pair (sym :presence) true) ...>) # presence: true
!(hash <$(pair (sym :strict) {true const}) ...>) # strict: true
!(hash <$(pair (sym {:if :unless}) _) ...>) # if: some_condition or unless: some_condition
]
)
PATTERN
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,20 @@ class Profile
RUBY
end

it 'does not register an offense with `if` option' do
expect_no_offenses(<<~RUBY)
belongs_to :user
validates :user, presence: true, if: -> { condition }
RUBY
end

it 'does not register an offense with `unless` option' do
expect_no_offenses(<<~RUBY)
belongs_to :user
validates :user, presence: true, unless: -> { condition }
RUBY
end

it 'does not register an offense with strict validation' do
expect_no_offenses(<<~RUBY)
belongs_to :user
Expand Down

0 comments on commit 1d33f84

Please sign in to comment.