Class: RuboCop::Cop::RSpecRails::NegationBeValid

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
ConfigurableEnforcedStyle
Defined in:
lib/rubocop/cop/rspec_rails/negation_be_valid.rb

Overview

Enforces use of ‘be_invalid` or `not_to` for negated be_valid.

Examples:

EnforcedStyle: not_to (default)

# bad
expect(foo).to be_invalid

# good
expect(foo).not_to be_valid

# good (with method chain)
expect(foo).to be_invalid.and be_odd

EnforcedStyle: be_invalid

# bad
expect(foo).not_to be_valid

# good
expect(foo).to be_invalid

# good (with method chain)
expect(foo).to be_invalid.or be_even

Constant Summary collapse

MSG =
'Use `expect(...).%<runner>s %<matcher>s`.'
RESTRICT_ON_SEND =
%i[be_valid be_invalid].freeze

Instance Method Summary collapse

Instance Method Details

#be_invalid?(node) ⇒ Object



45
46
47
# File 'lib/rubocop/cop/rspec_rails/negation_be_valid.rb', line 45

def_node_matcher :be_invalid?, <<~PATTERN
  (send ... :to (send nil? :be_invalid ...))
PATTERN

#not_to?(node) ⇒ Object



40
41
42
# File 'lib/rubocop/cop/rspec_rails/negation_be_valid.rb', line 40

def_node_matcher :not_to?, <<~PATTERN
  (send ... :not_to (send nil? :be_valid ...))
PATTERN

#on_send(node) ⇒ Object



49
50
51
52
53
54
55
56
57
# File 'lib/rubocop/cop/rspec_rails/negation_be_valid.rb', line 49

def on_send(node)
  return unless offense?(node.parent)

  add_offense(offense_range(node),
              message: message(node.method_name)) do |corrector|
    corrector.replace(node.parent.loc.selector, replaced_runner)
    corrector.replace(node.loc.selector, replaced_matcher)
  end
end