Writing tests for Ruby/Tk application

Tk allows to place widgets without explicitly specifying root window. It could become problem if You don’t have this window.

I got basic functionality of my application and then I wanted to develop it further more TDD way, since I anticipated some redesigns on the fly. Having then test suite will help me not break old features.

So I wrote simple tests, happily included tk, test/unit and my code library. I needed to calculate some metrics based on relations between widgets. In my tests in setup I was using something like this, which was taken directly from application code:

$widgets[:wg100] = Widget_100.new :text => 'wg100'
$widgets[:wg100].place :x => 10, :y => 10

As You can see I did not set :parent (line 1) which is OK in most cases. I didn’t expect any problems, since I didn’t wanted to run GUI. I just wanted to run some of my code, which needed widgets to have assigned coordinates.

Unfortunately I ran on strange behavior of Tk library – it was throwing strange errors – like NameError: uninitialized constant LineWidget::TkcLine , from places where I would not suspect (from lines where was no reference to TkcLine).

Reason – missing root window. Ruby/Tk does not force You to set explicitly root window, but it is good habit to always use :parent when creating new widgets. This way You will avoid such stupid mistakes – if I recollect correctly it took me an hour to get what was wrong. Learned hard way ;) Working setup was something like:

$root = TkRoot.new(:title=>'TDD & Tk', :height => 768, :width => 1024)

$widgets[:wg100] = Widget_100.new :text => 'wg100', :parent => $root
$widgets[:wg100].place :x => 10, :y => 10

Of course to run my tests, I didn’t fire up GUI (with Tk.mainloop). Just setup widgets, and do Your tests.

Leave a Reply

Your email address will not be published. Required fields are marked *