Class: RuboCop::Cop::Capybara::SpecificActions

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/capybara/specific_actions.rb

Overview

Checks for there is a more specific actions offered by Capybara.

Examples:


# bad
find('a').click
find('button.cls').click
find('a', exact_text: 'foo').click
find('div button').click

# good
click_link
click_button(class: 'cls')
click_link(exact_text: 'foo')
find('div').click_button

Constant Summary collapse

MSG =
"Prefer `%<good_action>s` over `find('%<selector>s').click`."
RESTRICT_ON_SEND =
%i[click].freeze
SPECIFIC_ACTION =
{
  'button' => 'button',
  'a' => 'link'
}.freeze

Instance Method Summary collapse

Instance Method Details

#click_on_selector(node) ⇒ Object



31
32
33
# File 'lib/rubocop/cop/capybara/specific_actions.rb', line 31

def_node_matcher :click_on_selector, <<~PATTERN
  (send _ :find (str $_) ...)
PATTERN

#on_send(node) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/rubocop/cop/capybara/specific_actions.rb', line 35

def on_send(node)
  click_on_selector(node.receiver) do |arg|
    next unless supported_selector?(arg)
    # Always check the last selector in the case of multiple selectors
    # separated by whitespace.
    # because the `.click` is executed on the element to
    # which the last selector points.
    next unless (selector = last_selector(arg))
    next unless (action = specific_action(selector))
    next unless replaceable?(node, arg, action)

    range = offense_range(node, node.receiver)
    add_offense(range, message: message(action, selector))
  end
end