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..
1
2 module InPlaceTesting
3 def self.included(klass)
4 old_method_added = klass.method(:method_added)
5 new_method_added = lambda do |m|
6 @@current_method = m
7 old_method_added.call m
8 end
9
10
11 (class << klass; self; end).send :define_method, :method_added, new_method_added
12
13 class << klass
14 def given(*args)
15 self.new.send @@current_method, *args
16 end
17 def method_should(message, params)
18 unless params[:return] == params[:when]
19 puts "\"#{@@current_method}\" fails to #{message} (returns #{params[:when]} instead of #{params[:return]})"
20 end
21 end
22 end
23
24 end
25
26 end
27
28 class DumbClass
29 include InPlaceTesting
30
31 def add(x,y)
32 x + y
33 end
34 method_should "add 5 and 4", :return => 9, :when => given(5, 4)
35
36 def subtract(x,y)
37 x - y
38 end
39 method_should "subtract 5 from 14", :return => 9, :when => given(14,5)
40
41 def increment(x)
42 x + 1
43 end
44 method_should "increment 12", :return => 13, :when => given(12)
45 end