Class: RuboCop::Cop::RSpec::Rails::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

EnforcedStyle: be_invalid

# bad
expect(foo).not_to be_valid

# good
expect(foo).to be_invalid

Constant Summary collapse

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

Instance Method Summary collapse

Methods inherited from Base

inherited, #on_new_investigation

Methods included from RSpec::Language::NodePattern

#block_or_numblock_pattern, #block_pattern, #numblock_pattern, #send_pattern

Methods included from RSpec::Language

#example?, #example_group?, #example_group_with_body?, #explicit_rspec?, #hook?, #include?, #let?, #rspec?, #shared_group?, #spec_group?, #subject?

Instance Method Details

#be_invalid?(node) ⇒ Object



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

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

#not_to?(node) ⇒ Object



35
36
37
# File 'lib/rubocop/cop/rspec/rails/negation_be_valid.rb', line 35

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

#on_send(node) ⇒ Object



44
45
46
47
48
49
50
51
52
# File 'lib/rubocop/cop/rspec/rails/negation_be_valid.rb', line 44

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