Skip to content

Instantly share code, notes, and snippets.

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 textarcana/132385 to your computer and use it in GitHub Desktop.
Save textarcana/132385 to your computer and use it in GitHub Desktop.
# === Running methods whose names begin with test_
#
# From {The Well Grounded Rubyist by David A. Black}[http://www.manning.com/black2/]
#
# This example implements a test framework. The really interesting
# part is the initial definition. self.inherited(c) is called when
# this class is inherited into a new class. The argument c is a
# reference to the new class. David then calls c.class_eval, whose
# argument is a block which will be executed in the scope of the new
# class. So when self.method_added is called, self now refers to the
# new (inheriting) class.
#
# Therefore when a method is added to any class that inherits from
# MicroTest, that method will trigger the execution of the
# c.class_eval do block.
require 'callertools'
class MicroTest
def self.inherited(c)
c.class_eval do
def self.method_added(m)
if m.to_s =~ /^test/
obj = self.new
if self.instance_methods.include?(:setup)
obj.setup
end
obj.send(m)
end
end
end
end
def assert(assertion)
if assertion
puts "Assertion passed"
true
else
puts "Assertion failed:"
stack = CallerTools::Stack.new
failure = stack.find {|call| call.meth !~ /assert/ }
puts failure
false
end
end
def assert_equal(expected, actual)
result assert(expected == actual)
puts "(#{actual} is not #{expected})" unless result
result
end
end
require 'test/unit'
class TestFoo < Test::Unit::TestCase
# === Master setup and teardown methods
# methods invoked before and after all tests
def self.master_setup
# stuff
end
def self.master_teardown
# stuff
end
# === override the existing suite method
def self.suite
mysuite = super
def mysuite.run(*args)
TestFoo.master_setup
super
TestFoo.master_teardown
end
end
# regular setup and teardown, followed by tests, as usual
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment