Created
June 19, 2009 03:18
-
-
Save textarcana/132385 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# === 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 | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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