module TestScore

Public Class Methods

log_results() click to toggle source
# File lib/testscore.rb, line 79
def self.log_results
  puts "\n\nReporting test suite performance to TestScore."
  host = ENV.fetch('TESTSCORE_REPORT_HOST', 'https://testscore.io')
  uri = URI("#{host}/results/#{@api_key}")
  req = Net::HTTP::Post.new(
    uri,
    'Content-Type' => 'application/json',
    'Content-Encoding' => 'gzip',
  )
  gzip = Zlib::GzipWriter.new(StringIO.new)
  gzip << { examples: @results }.to_json
  req.body = gzip.close.string
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = (uri.scheme == "https")
  response = http.request(req).body

  if response && response.length > 0
    jsonResponse = JSON.parse(response)

    if jsonResponse['error']
      puts "Unable to report results to TestScore: #{jsonResponse['error']}"
    end
  end
rescue => e
  puts "Unable to report results to TestScore: #{e.message}"
end
log_suite_started() click to toggle source
# File lib/testscore.rb, line 53
def self.log_suite_started
  @start_time = Time.now

  if rails?
    ActiveSupport::Notifications.subscribe('sql.active_record', ActiveRecord::QueryCounter.new)
  end
end
queries() click to toggle source
# File lib/testscore.rb, line 47
def self.queries
  return [] unless rails?

  ActiveRecord::QueryCounter.queries
end
rails?() click to toggle source
# File lib/testscore.rb, line 43
def self.rails?
  defined?(ActiveRecord) && defined?(ActiveSupport) && defined?(ActiveSupport::Notifications)
end
spec_ended(example) click to toggle source
# File lib/testscore.rb, line 70
def self.spec_ended(example)
  @results[example.id] = {
    duration: Time.now - @results[example.id][:started_at],
    description: example.description,
    metadata: example.metadata.slice(:line_number, :file_path),
    queries: queries
  }
end
spec_started(example) click to toggle source
# File lib/testscore.rb, line 61
def self.spec_started(example)
  @results ||= {}
  @results[example.id] = { started_at: Time.now }

  if rails?
    ActiveRecord::QueryCounter.queries = []
  end
end
start(api_key) click to toggle source
# File lib/testscore.rb, line 106
def self.start(api_key)
  @api_key = api_key

  RSpec.configure do |config|
    config.before(:each) do |example|
      TestScore.spec_started(example)
    end

    config.after(:each) do |example|
      TestScore.spec_ended(example)
    end

    config.before(:suite) do |suite|
      TestScore.log_suite_started
    end

    config.after(:suite) do |suite|
      TestScore.log_results
    end
  end
end