Sha256: 1d39cacfdfeec2a9177f1484fa66d0a1889f1ec58332458e2a799687cb9d1c41

Contents?: true

Size: 1.31 KB

Versions: 17

Compression:

Stored size: 1.31 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Minitest
      # Checks for opportunities to use `assert_output`.
      #
      # @example
      #   # bad
      #   $stdout = StringIO.new
      #   puts object.method
      #   $stdout.rewind
      #   assert_match expected, $stdout.read
      #
      #   # good
      #   assert_output(expected) { puts object.method }
      #
      class AssertOutput < Base
        include MinitestExplorationHelpers

        MSG = 'Use `assert_output` instead of mutating %<name>s.'
        OUTPUT_GLOBAL_VARIABLES = %i[$stdout $stderr].freeze

        def on_gvasgn(node)
          test_case_node = find_test_case(node)
          return unless test_case_node

          gvar_name = node.children.first
          return unless OUTPUT_GLOBAL_VARIABLES.include?(gvar_name)

          assertions(test_case_node).each do |assertion|
            add_offense(assertion, message: format(MSG, name: gvar_name)) if references_gvar?(assertion, gvar_name)
          end
        end

        private

        def find_test_case(node)
          node.each_ancestor.find { |ancestor| test_case?(ancestor) }
        end

        def references_gvar?(assertion, gvar_name)
          assertion.each_descendant(:gvar).any? { |d| d.children.first == gvar_name }
        end
      end
    end
  end
end

Version data entries

17 entries across 17 versions & 1 rubygems

Version Path
rubocop-minitest-0.36.0 lib/rubocop/cop/minitest/assert_output.rb
rubocop-minitest-0.35.1 lib/rubocop/cop/minitest/assert_output.rb
rubocop-minitest-0.35.0 lib/rubocop/cop/minitest/assert_output.rb
rubocop-minitest-0.34.5 lib/rubocop/cop/minitest/assert_output.rb
rubocop-minitest-0.34.4 lib/rubocop/cop/minitest/assert_output.rb
rubocop-minitest-0.34.3 lib/rubocop/cop/minitest/assert_output.rb
rubocop-minitest-0.34.2 lib/rubocop/cop/minitest/assert_output.rb
rubocop-minitest-0.34.1 lib/rubocop/cop/minitest/assert_output.rb
rubocop-minitest-0.34.0 lib/rubocop/cop/minitest/assert_output.rb
rubocop-minitest-0.33.0 lib/rubocop/cop/minitest/assert_output.rb
rubocop-minitest-0.32.2 lib/rubocop/cop/minitest/assert_output.rb
rubocop-minitest-0.32.1 lib/rubocop/cop/minitest/assert_output.rb
rubocop-minitest-0.32.0 lib/rubocop/cop/minitest/assert_output.rb
rubocop-minitest-0.31.1 lib/rubocop/cop/minitest/assert_output.rb
rubocop-minitest-0.31.0 lib/rubocop/cop/minitest/assert_output.rb
rubocop-minitest-0.30.0 lib/rubocop/cop/minitest/assert_output.rb
rubocop-minitest-0.29.0 lib/rubocop/cop/minitest/assert_output.rb