[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Unit testing idiom

Alex Young

6/13/2007 8:04:00 AM

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
1 Answer

Rick DeNatale

6/13/2007 2:08:00 PM

0

On 6/13/07, Alex Young <alex@blackkettle.org> 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.denh...