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

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
ConfigurableEnforcedStyle
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`.'
CAPYBARA_MATCHERS =
%w[
  selector css xpath text title current_path link button
  field checked_field unchecked_field select table
  sibling ancestor content
].freeze
POSITIVE_MATCHERS =
Set.new(CAPYBARA_MATCHERS) { |element| :"have_#{element}" }.freeze
NEGATIVE_MATCHERS =
Set.new(CAPYBARA_MATCHERS) { |element| :"have_no_#{element}" }
.freeze
RESTRICT_ON_SEND =
(POSITIVE_MATCHERS + NEGATIVE_MATCHERS).freeze

Instance Method Summary collapse

Instance Method Details

#have_no?(node) ⇒ Object



50
51
52
53
# File 'lib/rubocop/cop/capybara/negation_matcher.rb', line 50

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

#not_to?(node) ⇒ Object



44
45
46
47
# File 'lib/rubocop/cop/capybara/negation_matcher.rb', line 44

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

#on_send(node) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
# File 'lib/rubocop/cop/capybara/negation_matcher.rb', line 55

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