How to get count of RSpec examples already tested at runtime?

Viewed 25

How can I get the number of RSpec examples tested at runtime? I am maintaining a large test suite that takes a long time to run and seems to have a memory leak, and want to periodically output various diagnostics during the test run. In my spec_helper, I start a thread as in the code below. I would like to include in those diagnostics the number of tests already run. (The total number of tests to test would be great too, if that is available.)

  Thread.new do

    start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)

    classes = [
      SemanticLogger::Logger,
      SemanticLogger::Appender::IO,
      # ...
    ]

    loop do
      STDERR.puts
      classes.each do |klass|
        instance_count = ObjectSpace.each_object(klass).count
        uptime = (Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time).round(0)
        STDERR.puts format("%5d:  %10d  %s\n", uptime, instance_count, klass)
      end
      STDERR.puts
      sleep 10
    end
  end
1 Answers

One way to do this is to count the examples explicitly in a before(:each) block that applies to all test examples (for example, in a universally included spec_helper.rb file). For example:

RSpec.configure do |config|
  $rspec_example_count = 0

  config.before(:each) do |example|
    $rspec_example_count += 1

(If you can get by without using a global variable, even better, but the global variable is probably fine given that it is only used in an rspec test suite.)

Related