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

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

Overview

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

Examples:

EnforcedStyle: not_to (default)

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

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

EnforcedStyle: have_no

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

# good
expect(page).to have_no_selector
expect(page).to have_no_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
].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

Methods inherited from Base

inherited, #on_new_investigation

Methods included from RSpec::Language::NodePattern

#block_pattern, #numblock_pattern, #send_pattern

Methods included from RSpec::Language

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

Instance Method Details

#have_no?(node) ⇒ Object



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

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

#not_to?(node) ⇒ Object



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

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

#on_send(node) ⇒ Object



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

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

  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