Sha256: b870abad485e135b2dc7046a5590d631aa819bf761b101fa4b001c37ed222b62

Contents?: true

Size: 1.93 KB

Versions: 6

Compression:

Stored size: 1.93 KB

Contents

# frozen_string_literal: true

require 'tempfile'

# This module provides methods that make it easier to test Cops.
module CopHelper
  extend RSpec::SharedContext

  let(:ruby_version) { 2.4 }
  let(:rails_version) { false }

  def inspect_source_file(source)
    Tempfile.open('tmp') { |f| inspect_source(source, f) }
  end

  def inspect_source(source, file = nil)
    RuboCop::Formatter::DisabledConfigFormatter.config_to_allow_offenses = {}
    RuboCop::Formatter::DisabledConfigFormatter.detected_styles = {}
    processed_source = parse_source(source, file)
    raise 'Error parsing example code' unless processed_source.valid_syntax?

    _investigate(cop, processed_source)
  end

  def parse_source(source, file = nil)
    if file&.respond_to?(:write)
      file.write(source)
      file.rewind
      file = file.path
    end

    RuboCop::ProcessedSource.new(source, ruby_version, file)
  end

  def autocorrect_source_file(source)
    Tempfile.open('tmp') { |f| autocorrect_source(source, f) }
  end

  def autocorrect_source(source, file = nil)
    RuboCop::Formatter::DisabledConfigFormatter.config_to_allow_offenses = {}
    RuboCop::Formatter::DisabledConfigFormatter.detected_styles = {}
    cop.instance_variable_get(:@options)[:auto_correct] = true
    processed_source = parse_source(source, file)
    _investigate(cop, processed_source)

    @last_corrector.rewrite
  end

  def _investigate(cop, processed_source)
    team = RuboCop::Cop::Team.new([cop], nil, raise_error: true)
    report = team.investigate(processed_source)
    @last_corrector = report.correctors.first || RuboCop::Cop::Corrector.new(processed_source)
    report.offenses
  end
end

module RuboCop
  module Cop
    # Monkey-patch Cop for tests to provide easy access to messages and
    # highlights.
    class Cop
      def messages
        offenses.sort.map(&:message)
      end

      def highlights
        offenses.sort.map { |o| o.location.source }
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 2 rubygems

Version Path
rubocop-0.89.1 lib/rubocop/rspec/cop_helper.rb
rubocop-0.89.0 lib/rubocop/rspec/cop_helper.rb
rubocop-0.88.0 lib/rubocop/rspec/cop_helper.rb
rbhint-0.87.1.rc1 lib/rubocop/rspec/cop_helper.rb
rubocop-0.87.1 lib/rubocop/rspec/cop_helper.rb
rubocop-0.87.0 lib/rubocop/rspec/cop_helper.rb