Skip to content

Instantly share code, notes, and snippets.

@dcorrigan
Last active January 16, 2018 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcorrigan/e3f2f0e7ed69e990e15063090dd115da to your computer and use it in GitHub Desktop.
Save dcorrigan/e3f2f0e7ed69e990e15063090dd115da to your computer and use it in GitHub Desktop.
Console/REPL Test Runner

A Quick REPL Test Runner

This is a small helper class demonstrating how to run unit tests in IRB or a similar Ruby REPL:

# console_runner.rb
require 'test/unit/ui/console/testrunner'

class ConsoleRunner
  def initialize(file_list)
    @file_list = file_list
  end

  def run_test(test_file_str)
    Test::Unit::UI::Console::TestRunner.run(test_class(test_file_str))
  end

  def load_tests
    @file_list.each { |f| load f }
  end

  private

  def test_class(test_file_str)
    f = file_match(test_file_str)
    raise ArgumentError, "No matching test for #{test_file_str}!" if f.nil?
    file_classes[f]
  end

  def file_match(test_file_str)
    @file_list.find { |x| x[test_file_str] }
  end

  def file_classes
    @file_classes ||= Hash[@file_list.map { |x| [x, find_class_str(x)] }]
  end

  def find_class_str(f)
    eval(File.read(f)[/(?<=class )\w+/])
  end
end

Support you had the following simple test class:

# test/some_test.rb
require 'test/unit'

class SomeTest < Test::Unit::TestCase
  def test_something
    assert true
  end
end

Load IRB with the console_runner.rb:

$ irb -r ./console_runner.rb

You initialize an instance with a list of files and then use that instance to run your tests. Do this in IRB, then load the tests:

> runner = ConsoleRunner.new(Dir.glob('./test/*.rb'))
> runner.load_tests

Now, the runner will try to match any string you give its #run_test method against its list of existing test classes. It will run the corresponding tests for the first file that matches. If it can't find a match, it will raise an error.

> runner.run_test 'some'
Loaded suite SomeTest
Started
.
Finished in 0.000718 seconds.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment