Sha256: 844bddf73c121a57a8a61458ea3a2987e2a1594510562622b534a6927b9d327a

Contents?: true

Size: 1.61 KB

Versions: 4

Compression:

Stored size: 1.61 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Minitest
      # This cop enforces the test to use `assert_path_exists`
      # instead of using `assert(File.exist?(path))`.
      #
      # @example
      #   # bad
      #   assert(File.exist?(path))
      #   assert(File.exist?(path), 'message')
      #
      #   # good
      #   assert_path_exists(path)
      #   assert_path_exists(path, 'message')
      #
      class AssertPathExists < Cop
        MSG = 'Prefer using `%<good_method>s` over `%<bad_method>s`.'

        def_node_matcher :assert_file_exists, <<~PATTERN
          (send nil? :assert
            (send
              (const _ :File) {:exist? :exists?} $_)
              $...)
        PATTERN

        def on_send(node)
          assert_file_exists(node) do |path, failure_message|
            failure_message = failure_message.first
            good_method = build_good_method(path, failure_message)
            message = format(MSG, good_method: good_method, bad_method: node.source)

            add_offense(node, message: message)
          end
        end

        def autocorrect(node)
          assert_file_exists(node) do |path, failure_message|
            failure_message = failure_message.first

            lambda do |corrector|
              replacement = build_good_method(path, failure_message)
              corrector.replace(node, replacement)
            end
          end
        end

        private

        def build_good_method(path, message)
          args = [path.source, message&.source].compact.join(', ')
          "assert_path_exists(#{args})"
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
rubocop-minitest-0.10.3 lib/rubocop/cop/minitest/assert_path_exists.rb
rubocop-minitest-0.10.2 lib/rubocop/cop/minitest/assert_path_exists.rb
rubocop-minitest-0.10.1 lib/rubocop/cop/minitest/assert_path_exists.rb
rubocop-minitest-0.10.0 lib/rubocop/cop/minitest/assert_path_exists.rb