Skip to content

Instantly share code, notes, and snippets.

@beccasaurus
Last active June 29, 2019 03:59
Show Gist options
  • Save beccasaurus/329efa0b615ca5bdb66249ff6a633e12 to your computer and use it in GitHub Desktop.
Save beccasaurus/329efa0b615ca5bdb66249ff6a633e12 to your computer and use it in GitHub Desktop.
πŸ’Ž Minimal Pure Ruby Testing

Minimal Ruby Testing πŸ’Ž

...because Ruby doesn't ship with a testing framework (anymore)

$ testing.rb is 50 lines of code

require "testing"

test "String equal?" do
  assert "hello" == "hello"
end

test "Are these numbers equal?" do
  assert 5 == 6
end

test "This is pending, I'll do it later"

test "Describe why it blew up" do
  assert 1 == 2, "number equality"
end
$ ruby mytest.rb
String equal? [OK]

Are these numbers equal? [FAIL]
assertion failed @ mytest.rb:8
=> assert 5 == 6

This is pending, I'll do it later [PENDING]
Describe why it blew up [FAIL]
number equality @ mytest.rb:14
=> assert 1 == 2, "number equality"
#! /usr/bin/env ruby
# Minimal Testing – Pure Ruby πŸ’Ž (50 LOC)
def green message; "\e[32m#{message}\e[0m"; end
def red message; "\e[31m#{message}\e[0m"; end
def yellow message; "\e[33m#{message}\e[0m"; end
class AssertionError < StandardError; end
def assert condition, message = "assertion failed"
raise AssertionError, message unless condition
end
def assert_equals a, b, message = nil
assert a == b, "Expected #{a.inspect} to equal #{b.inspect}"
end
def assert_contains collection, item, message = nil
assert collection.include?(item),
"Expected #{collection.inspect} to include #{item.inspect}"
end
def tests; $_tests_ ||= {}; end
def test description, &block; tests[description] = block; end
def print_error e
print e.message
e.backtrace.detect {|l| l =~ /^(?<filepath>\w+\.rb):(?<line_number>\d+)/ }
if $1
puts " @ #{$1}:#{$2}" if $1
puts "=> " + File.read($~[:filepath]).lines[$~[:line_number].to_i - 1].strip
end
puts
puts e.backtrace if ENV["VERBOSE"] == "true"
end
def run_tests!
all_passed = true
tests.select {|d,b| if m = ENV["MATCH"]; d.include? m; else; true; end }.
each do |description, block|
begin
if block.nil?; puts "#{description} [#{yellow "PENDING"}]"; next; end
print "#{description} "
block.call
puts "[#{green "OK"}]\n\n"
rescue AssertionError => e
all_passed = false
puts "[#{red "FAIL"}]"
print_error e
rescue Exception => e
all_passed = false
puts "[#{red "ERROR"}]"
print_error e
end
end
exit 1 unless all_passed
end
at_exit { run_tests! }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment