Module: TestScore

Defined in:
lib/testscore.rb

Class Method Summary collapse

Class Method Details

.log_resultsObject



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# 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_startedObject



53
54
55
56
57
58
59
# 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

.queriesObject



47
48
49
50
51
# File 'lib/testscore.rb', line 47

def self.queries
  return [] unless rails?

  ActiveRecord::QueryCounter.queries
end

.rails?Boolean

Returns:

  • (Boolean)


43
44
45
# File 'lib/testscore.rb', line 43

def self.rails?
  defined?(ActiveRecord) && defined?(ActiveSupport) && defined?(ActiveSupport::Notifications)
end

.spec_ended(example) ⇒ Object



70
71
72
73
74
75
76
77
# 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..slice(:line_number, :file_path),
    queries: queries
  }
end

.spec_started(example) ⇒ Object



61
62
63
64
65
66
67
68
# 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) ⇒ Object



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# 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