The Existence Test

by Gregory Brown

I think most Rubyists have picked up a good trick or two from Jim Weirich. Though it's only a tiny part of his latest article (Using Flexmock to Test Computational Fluid Dynamics Code), I got excited to see his 'Existence Test' in his code:


def test_initial_conditions
q = F3DQueue.new
assert_not_nil q
end


Looks pretty simple, eh? You might be quick to say that this doesn't do anything. However, it is actually a pretty clever practice. This test makes sure the tests themselves are working as expected. I was already in the habit of starting with a failure, usually something like:


def test_doomed
flunk
end


The purpose of the above is simply to make sure your tests are picked up within your suite, and aren't being overlooked by your Rakefile, autotest, or whatever runner you're using. But the existence test actually goes a little farther. Because you're initializing an object, you're making sure that the files you need to be loading are present, that you can build your objects, *and* that your tests are hooked up.

After you've got a couple tests passing, you can remove this sanity check or morph it into a setup(), whatever makes sense.

Many people think this is a little paranoid, and most of the time, it is. Still, all it takes is one bad experience coding under falsely passing tests, and you'll be converted in no time. :)

1 Comments

ken
2007-10-18 12:46:44
I don't get it. Unless you're afraid you might have accidentally said "def F3DQueue.new: return nil; end", what does the assertion add?


Sure, put "F3DQueue.new" in there to make sure your class is getting loaded and can instantiate itself. But why the assert_not_nil?