Hi all,
It’s always bothered me having code and unit tests in different places -
keeping unit tests near the code they are testing has to be a good
thing, right?
Given the above, I stumbled on the following idiom:
$ cat testable.rb
module Test; module Unit; class TestCase; end; end; end
module Testable
def test_case(&block)
Class.new(Test::Unit::TestCase).module_eval &block
end
end
$ cat builtin_tests.rb
require ‘testable’
class MyWorkingClass
extend Testable
def foo(a,b)
return a+b
end
test_case {
def test_foo_null
assert_equal 2, MyWorkingClass.new.foo(1,1)
end
}
end
if FILE == $0
puts MyWorkingClass.new.foo(1,1)
end
$ ruby builtin_tests.rb
2
$ testrb builtin_tests.rb
Loaded suite builtin_tests.rb
Started
.
Finished in 0.00095 seconds.
1 tests, 1 assertions, 0 failures, 0 errors
$
Just thought I’d share
Are there any drawbacks to this method that
I haven’t seen yet?
On 6/13/07, Alex Y. [email protected] wrote:
Hi all,
It’s always bothered me having code and unit tests in different places -
keeping unit tests near the code they are testing has to be a good
thing, right?
I don’t know that I agree with your premise. While it might seem
convenient to combine tests with the artifacts they test, in general
I think that separating them is a good thing.
Having separate tests acts as a sort of double-entry bookkeeping
system. If they are combined there’s the possbility of ‘cooking the
books’ either deliberately or unintentionally.
For simple things, such as trying something out, or demonstrating your
ruby-foo on posts here, combining the tests and code being tested
might be alright, but I think it’s an idea best used in moderation.
For anything larger, I’d advocate for setting up a system for locating
the test code, such as the directory structure used by Rails.
–
Rick DeNatale
My blog on Ruby
http://talklikeaduck.denhaven2.com/