Class: RuboCop::Cop::Capybara::NegationMatcher

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
ConfigurableEnforcedStyle, CapybaraHelp
Defined in:
lib/rubocop/cop/capybara/negation_matcher.rb

Overview

Enforces use of ‘have_no_*` or `not_to` for negated expectations.

Examples:

EnforcedStyle: have_no (default)

# bad
expect(page).not_to have_selector 'a'
expect(page).not_to have_css('a')

# good
expect(page).to have_no_selector 'a'
expect(page).to have_no_css('a')

EnforcedStyle: not_to

# bad
expect(page).to have_no_selector 'a'
expect(page).to have_no_css('a')

# good
expect(page).not_to have_selector 'a'
expect(page).not_to have_css('a')

Constant Summary collapse

MSG =
'Use `expect(...).%<runner>s %<matcher>s`.'
RESTRICT_ON_SEND =
(POSITIVE_MATCHERS + NEGATIVE_MATCHERS).freeze

Constants included from CapybaraHelp

CapybaraHelp::CAPYBARA_MATCHERS, CapybaraHelp::COMMON_OPTIONS, CapybaraHelp::NEGATIVE_MATCHERS, CapybaraHelp::POSITIVE_MATCHERS, CapybaraHelp::SPECIFIC_OPTIONS, CapybaraHelp::SPECIFIC_PSEUDO_CLASSES

Instance Method Summary collapse

Methods included from CapybaraHelp

common_attributes?, include_option?, replaceable_attributes?, replaceable_element?, replaceable_option?, replaceable_pseudo_class?, replaceable_pseudo_class_not?, replaceable_pseudo_classes?, replaceable_to_link?

Instance Method Details

#have_no?(node) ⇒ Object

[View source]

41
42
43
44
# File 'lib/rubocop/cop/capybara/negation_matcher.rb', line 41

def_node_matcher :have_no?, <<~PATTERN
  (send ... :to
    (send nil? %NEGATIVE_MATCHERS ...))
PATTERN

#not_to?(node) ⇒ Object

[View source]

35
36
37
38
# File 'lib/rubocop/cop/capybara/negation_matcher.rb', line 35

def_node_matcher :not_to?, <<~PATTERN
  (send ... {:not_to :to_not}
    (send nil? %POSITIVE_MATCHERS ...))
PATTERN

#on_send(node) ⇒ Object

[View source]

46
47
48
49
50
51
52
53
54
55
56
# File 'lib/rubocop/cop/capybara/negation_matcher.rb', line 46

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

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