Class: RuboCop::Cop::RSpecRails::MinitestAssertions

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

Overview

Check if using Minitest-like matchers.

Check the use of minitest-like matchers starting with ‘assert_` or `refute_`.

Examples:

# bad
assert_equal(a, b)
assert_equal a, b, "must be equal"
assert_not_includes a, b
refute_equal(a, b)
assert_nil a
refute_empty(b)
assert_true(a)
assert_false(a)

# good
expect(b).to eq(a)
expect(b).to(eq(a), "must be equal")
expect(a).not_to include(b)
expect(b).not_to eq(a)
expect(a).to eq(nil)
expect(a).not_to be_empty
expect(a).to be(true)
expect(a).to be(false)

Defined Under Namespace

Classes: BasicAssertion, EmptyAssertion, EqualAssertion, FalseAssertion, InDeltaAssertion, IncludesAssertion, InstanceOfAssertion, KindOfAssertion, MatchAssertion, NilAssertion, PredicateAssertion, TrueAssertion

Constant Summary collapse

MSG =
'Use `%<prefer>s`.'
ASSERTION_MATCHERS =

TODO: replace with ‘BasicAssertion.subclasses` in Ruby 3.1+

constants(false).filter_map do |c|
  const = const_get(c)

  const if const.is_a?(Class) && const.superclass == BasicAssertion
end
RESTRICT_ON_SEND =
ASSERTION_MATCHERS.flat_map { |m| m::MATCHERS }

Instance Method Summary collapse

Instance Method Details

#message(preferred) ⇒ Object



344
345
346
# File 'lib/rubocop/cop/rspec_rails/minitest_assertions.rb', line 344

def message(preferred)
  format(MSG, prefer: preferred)
end

#on_assertion(node, assertion) ⇒ Object



337
338
339
340
341
342
# File 'lib/rubocop/cop/rspec_rails/minitest_assertions.rb', line 337

def on_assertion(node, assertion)
  preferred = assertion.replaced(node)
  add_offense(node, message: message(preferred)) do |corrector|
    corrector.replace(node, preferred)
  end
end

#on_send(node) ⇒ Object



325
326
327
328
329
330
331
332
333
334
335
# File 'lib/rubocop/cop/rspec_rails/minitest_assertions.rb', line 325

def on_send(node)
  ASSERTION_MATCHERS.each do |m|
    m.minitest_assertion(node) do |*args|
      assertion = m.match(*args)

      next if assertion.nil?

      on_assertion(node, assertion)
    end
  end
end