Unit testing idiom

A

Alex Young

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
 
R

Rick DeNatale

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top