Class: RuboCop::Cop::Minitest::AssertMatch

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
ArgumentRangeHelper
Defined in:
lib/rubocop/cop/minitest/assert_match.rb

Overview

Enforces the test to use ‘assert_match` instead of using `assert(matcher.match(string))`.

Examples:

# bad
assert(matcher.match(string))
assert(matcher.match?(string))
assert(matcher =~ string)
assert_operator(matcher, :=~, string)
assert(matcher.match(string), 'message')

# good
assert_match(regex, string)
assert_match(matcher, string, 'message')

Constant Summary collapse

MSG =
'Prefer using `assert_match(%<preferred>s)`.'
RESTRICT_ON_SEND =
%i[assert assert_operator].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object

rubocop:disable Metrics/AbcSize



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/rubocop/cop/minitest/assert_match.rb', line 36

def on_send(node)
  assert_match(node) do |expected, actual, rest_args|
    basic_arguments = order_expected_and_actual(expected, actual)
    preferred = (message_arg = rest_args.first) ? "#{basic_arguments}, #{message_arg.source}" : basic_arguments
    message = format(MSG, preferred: preferred)

    add_offense(node, message: message) do |corrector|
      corrector.replace(node.loc.selector, 'assert_match')

      range = if node.method?(:assert)
                node.first_argument
              else
                node.first_argument.source_range.begin.join(node.arguments[2].source_range.end)
              end

      corrector.replace(range, basic_arguments)
    end
  end
end