DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
In Place Testing For Ruby Methods
This is something kinda experimental I'm working on. Testing is cool, but I hate that it's separate from my code. Perhaps that's stupidity on my part, but I wanted to see if there's a way to bring the lowest level of testing directly into the class..
module InPlaceTesting
def self.included(klass)
old_method_added = klass.method(:method_added)
new_method_added = lambda do |m|
@@current_method = m
old_method_added.call m
end
# Next line inspired by http://utils.ning.com/ruby/dbc.rb by Brian McCallister and Martin Traverso
(class << klass; self; end).send :define_method, :method_added, new_method_added
class << klass
def given(*args)
self.new.send @@current_method, *args
end
def method_should(message, params)
unless params[:return] == params[:when]
puts "\"#{@@current_method}\" fails to #{message} (returns #{params[:when]} instead of #{params[:return]})"
end
end
end
end
end
class DumbClass
include InPlaceTesting
def add(x,y)
x + y
end
method_should "add 5 and 4", :return => 9, :when => given(5, 4)
def subtract(x,y)
x - y
end
method_should "subtract 5 from 14", :return => 9, :when => given(14,5)
def increment(x)
x + 1
end
method_should "increment 12", :return => 13, :when => given(12)
end






Comments
Snippets Manager replied on Mon, 2012/05/07 - 2:37pm
Snippets Manager replied on Mon, 2007/04/02 - 5:46am
Snippets Manager replied on Mon, 2012/05/07 - 2:37pm