Politics, Programming and Possibilities
19 Jun
I’ve been in contact with the authors of two tools, doctest and rubydoctest, to bring a new, unified Ruby DocTest tool to the community.
I am confident this tool will improve the quality of my own software, and I think it might help you too. The tool allows you to put tests right into ruby code (in the comments) and provides a way to reliably keep the tests up to date, right with the code.
Here’s how it works (the following is taken from the doctests within Ruby DocTest itself):
# doctest: A statement should parse out a '>>' irb prompt
# >> s = RubyDocTest::Statement.new([">> a = 1"])
# >> s.source_code
# => "a = 1"
#
# doctest: More than one line should get included,
# if indentation so indicates
# >> s = RubyDocTest::Statement.new([">> b = 1 +", " 1",
# "not part of the statement"])
# >> s.source_code
# => "b = 1 +\n1"
#
# doctest: Lines indented by ?> should have the ?> removed.
# >> s = RubyDocTest::Statement.new([">> b = 1 +", "?> 1"])
# >> s.source_code
# => "b = 1 +\n1"
The “doctest:” directive gives the test a name. The “>>” marker says “execute this code” and the “=>” marker says “compare the result with the following expectation”. These markers are taken directly from irb, which–wonder of wonders–means you can copy-paste an irb session into your code and have that become your test.
You can also put a “!!!” marker anywhere in the comments (it has to be the first thing after the #, actually) and it will take you into an interactive ruby (irb) session. For example, let’s say you had this much working:
# >> s = "hello, my name is Simon"
and you realize you don’t know how to use the [] regexp notation on this string (for example). You could add:
# >> s = "hello, my name is Simon"
# !!!
then run the test suite (e.g. run “rubydoctest yourfile.rb”) and then the tests will execute up to that point and take you into the irb session where “s” is available to be played with. Then you can copy / paste the result back to your code and you have a working test.
To install it:
git clone git://github.com/canadaduane/\ rubydoctest.git rubydoctest cd rubydoctest rake manifest:refresh rake gem sudo rake install
This will give you the “rubydoctest” command line tool.
Enjoy!
Leave a reply