Skip to content

Commit bd7ee99

Browse files
authored
Merge pull request #1140 from koic/fix_false_positives_for_redundant_presence_validation_on_belongs_to
[Fix #1105] Fix false positives for `Rails/RedundantPresenceValidationOnBelongsTo`
2 parents ebfb3ef + 1cca3cc commit bd7ee99

3 files changed

+22
-0
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
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][])

lib/rubocop/cop/rails/redundant_presence_validation_on_belongs_to.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,12 @@ class RedundantPresenceValidationOnBelongsTo < Base
5353
# @example source that matches - by a foreign key
5454
# validates :user_id, presence: true
5555
#
56+
# @example source that DOES NOT match - if condition
57+
# validates :user_id, presence: true, if: condition
58+
#
59+
# @example source that DOES NOT match - unless condition
60+
# validates :user_id, presence: true, unless: condition
61+
#
5662
# @example source that DOES NOT match - strict validation
5763
# validates :user_id, presence: true, strict: true
5864
#
@@ -65,6 +71,7 @@ class RedundantPresenceValidationOnBelongsTo < Base
6571
$[
6672
(hash <$(pair (sym :presence) true) ...>) # presence: true
6773
!(hash <$(pair (sym :strict) {true const}) ...>) # strict: true
74+
!(hash <$(pair (sym {:if :unless}) _) ...>) # if: some_condition or unless: some_condition
6875
]
6976
)
7077
PATTERN

spec/rubocop/cop/rails/redundant_presence_validation_on_belongs_to_spec.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,20 @@ class Profile
271271
RUBY
272272
end
273273

274+
it 'does not register an offense with `if` option' do
275+
expect_no_offenses(<<~RUBY)
276+
belongs_to :user
277+
validates :user, presence: true, if: -> { condition }
278+
RUBY
279+
end
280+
281+
it 'does not register an offense with `unless` option' do
282+
expect_no_offenses(<<~RUBY)
283+
belongs_to :user
284+
validates :user, presence: true, unless: -> { condition }
285+
RUBY
286+
end
287+
274288
it 'does not register an offense with strict validation' do
275289
expect_no_offenses(<<~RUBY)
276290
belongs_to :user

0 commit comments

Comments
 (0)