diff --git a/CHANGELOG.md b/CHANGELOG.md index 5bf4724148e..ebcd6099bac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## master (unreleased) +### Bug fixes + +* [#6882](https://github.com/rubocop-hq/rubocop/issues/6882): Fix an error for `Rails/RedundantAllowNil` when not using both `allow_nil` and `allow_blank`. ([@koic][]) + ## 0.67.1 (2019-04-04) ### Changes diff --git a/lib/rubocop/cop/rails/redundant_allow_nil.rb b/lib/rubocop/cop/rails/redundant_allow_nil.rb index 5388f803a16..be75c159246 100644 --- a/lib/rubocop/cop/rails/redundant_allow_nil.rb +++ b/lib/rubocop/cop/rails/redundant_allow_nil.rb @@ -39,14 +39,12 @@ def on_send(node) return unless node.method_name == :validates allow_nil, allow_blank = find_allow_nil_and_allow_blank(node) + return unless allow_nil && allow_blank + allow_nil_val = allow_nil.children.last allow_blank_val = allow_blank.children.last - if allow_nil_val.type == allow_blank_val.type - add_offense(allow_nil, message: MSG_SAME) - elsif allow_nil_val.false_type? && allow_blank_val.true_type? - add_offense(allow_nil, message: MSG_ALLOW_NIL_FALSE) - end + offense(allow_nil_val, allow_blank_val, allow_nil) end def autocorrect(node) @@ -66,6 +64,14 @@ def autocorrect(node) private + def offense(allow_nil_val, allow_blank_val, allow_nil) + if allow_nil_val.type == allow_blank_val.type + add_offense(allow_nil, message: MSG_SAME) + elsif allow_nil_val.false_type? && allow_blank_val.true_type? + add_offense(allow_nil, message: MSG_ALLOW_NIL_FALSE) + end + end + def find_allow_nil_and_allow_blank(node) allow_nil = nil allow_blank = nil diff --git a/spec/rubocop/cop/rails/redundant_allow_nil_spec.rb b/spec/rubocop/cop/rails/redundant_allow_nil_spec.rb index 197dba37054..0ce9ffd5a9e 100644 --- a/spec/rubocop/cop/rails/redundant_allow_nil_spec.rb +++ b/spec/rubocop/cop/rails/redundant_allow_nil_spec.rb @@ -3,6 +3,30 @@ RSpec.describe RuboCop::Cop::Rails::RedundantAllowNil do subject(:cop) { described_class.new } + context 'when not using both `allow_nil` and `allow_blank`' do + it 'registers no offense' do + expect_no_offenses(<<-RUBY.strip_indent) + validates :email, presence: true + RUBY + end + end + + context 'when using only `allow_nil`' do + it 'registers no offense' do + expect_no_offenses(<<-RUBY.strip_indent) + validates :email, allow_nil: true + RUBY + end + end + + context 'when using only `allow_blank`' do + it 'registers no offense' do + expect_no_offenses(<<-RUBY.strip_indent) + validates :email, allow_blank: true + RUBY + end + end + context 'when both allow_nil and allow_blank are true' do it 'registers an offense' do expect_offense(<<-RUBY.strip_indent)