From: Massimiliano Mirra - bard Date: 2004-08-28T05:40:33+09:00 Subject: Literate testing? I was documenting a class and found myself often copying unit tests and pasting them as examples. I think I also read something about tests embedded in doc strings in Python. So in the interest of DRY I figured something like this could be desirable: class Calculator extend Literate example # Addition add(2, 8) == 10 end def add(a, b) return a + b end end I then came up with a stupid but working proof of concept: class Calculator extend Literate example(__FILE__, __LINE__) do |calc| # Addition calc.add(2, 8) == 10 end def add(a, b) return a + b end example(__FILE__, __LINE__) do |calc| # Integer division calc.div(10, 2) == 5 end def div(a, b) return a / b + 1 end end When examples are run as tests and a test does not pass (as the div example above), this is the output: Test passed at line 17. Test failed at line 27: # Integer division calc.div(10, 2) == 5 This is the rest: module Literate def examples @examples ||= [] end def example(file, line, &example) @examples ||= [] @examples << [file, line, example] end end Calculator.examples.each do |file, line, example| c = Calculator.new if example.call(c) puts "Test passed at line #{line}." else puts "Test failed at line #{line}:" puts File.readlines(file)[line, 2] end end What do you think? Massimiliano