Sha256: a5df7281de907f9ba404900686e5402ccc2d6b4833a732f3297b81c2803efeae

Contents?: true

Size: 1.3 KB

Versions: 4

Compression:

Stored size: 1.3 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Minitest
      # This cop enforces the test to use `assert(actual)`
      # instead of using `assert_equal(true, actual)`.
      #
      # @example
      #   # bad
      #   assert_equal(true, actual)
      #   assert_equal(true, actual, 'the message')
      #
      #   # good
      #   assert(actual)
      #   assert(actual, 'the message')
      #
      class AssertTruthy < Cop
        MSG = 'Prefer using `assert(%<arguments>s)` over ' \
              '`assert_equal(true, %<arguments>s)`.'

        def_node_matcher :assert_equal_with_truthy, <<~PATTERN
          (send nil? :assert_equal true $_ $...)
        PATTERN

        def on_send(node)
          assert_equal_with_truthy(node) do |actual, rest_receiver_arg|
            message = rest_receiver_arg.first

            arguments = [actual.source, message&.source].compact.join(', ')

            add_offense(node, message: format(MSG, arguments: arguments))
          end
        end

        def autocorrect(node)
          lambda do |corrector|
            arguments = node.arguments.reject(&:true_type?)
            replacement = arguments.map(&:source).join(', ')
            corrector.replace(node.loc.expression, "assert(#{replacement})")
          end
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
rubocop-minitest-0.5.0 lib/rubocop/cop/minitest/assert_truthy.rb
rubocop-minitest-0.4.1 lib/rubocop/cop/minitest/assert_truthy.rb
rubocop-minitest-0.4.0 lib/rubocop/cop/minitest/assert_truthy.rb
rubocop-minitest-0.3.0 lib/rubocop/cop/minitest/assert_truthy.rb