Class: RuboCop::Cop::RSpec::MatchWithSimpleRegex

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/rspec/match_with_simple_regex.rb

Overview

Enforces the use of ‘include` matcher instead of `match` when the matcher is a simple string literal without regex-specific features.

When ‘match` is used with a regex that contains only literal characters (no anchors, character classes, quantifiers, alternations, or metacharacters), it’s clearer to use the ‘include` matcher instead.

Examples:

# bad
expect('foobar').to match(/foo/)
expect(response.body).to match(/http:\/\/example\.com/)

# good
expect('foobar').to include('foo')
expect(response.body).to include('http://example.com')

# good - regex features needed
expect('foobar').to match(/^foo/)     # anchor
expect('foobar').to match(/foo\d+/)   # quantifier
expect('foobar').to match(/foo[ob]/)  # character class

Constant Summary collapse

MSG =
'Prefer using `include(%<string>s)` when the regex is a simple ' \
'string literal.'
RESTRICT_ON_SEND =
%i[match].freeze

Instance Method Summary collapse

Methods inherited from Base

inherited, #on_new_investigation

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

#match_with_regexp?(node) ⇒ Object



37
38
39
# File 'lib/rubocop/cop/rspec/match_with_simple_regex.rb', line 37

def_node_matcher :match_with_regexp?, <<~PATTERN
  (send nil? :match $regexp)
PATTERN

#on_send(node) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/rubocop/cop/rspec/match_with_simple_regex.rb', line 41

def on_send(node)
  match_with_regexp?(node) do |regexp|
    next unless simple_regexp?(regexp)

    string_literal = regexp_to_string(regexp)
    message = format(MSG, string: string_literal)

    add_offense(node, message: message) do |corrector|
      corrector.replace(node, "include(#{string_literal})")
    end
  end
end