David J Rice

The blog of freelance Designer & Developer, David Rice.

12 Jul 2006

Drying up your unit tests

So you’ve started unit testing, yet doing unit tests on models for basic crud operations usually leads to a lot of repetition.

  1. How many fixtures are there in the database
  2. Try and create a new record
  3. Assert some stuff
  4. Assert that the new record was created

and also the inverse

  1. How many fixtures are there in the database
  2. Try and create a new record
  3. Assert some stuff
  4. Assert that the new record was not created

That’s were assert_difference and assert_no_difference comes in.

assert_difference

Using Marcel Molina’s excellent assert_difference we can encapsulate a lot of this common code with a simple helper method. (follow the link for the code and place in your test_helper.rb file)

assert_no_difference

Simply a wrapper for the assert_difference helper, I couldn’t find this online so just posting it here for posterity.

  def assert_no_difference(object, method, &block)
      assert_difference object, method, 0, &block
  end

Autotest

I found this little gem (pun not intended) from a post by Geoffrey Grosenbach

What it does is automatically check the files in the rails directory for changes, and run the appropriate tests. This can be really handy if you’re doing a lot of work in a specific model and you’ve lots of other tests… as it will only run the tests corresponding to the files you’ve changed, saving quite some time.

Installation is easy

sudo gem install ZenTest

Kick off the unit tests with

autotest -rails

Getting better test failure notification

After a while using autotest I thought i could save even more time if i didn’t keep having to flick between textmate and iTerm. Then the other day I noticed an excellent plugin by Blake Waters, that integrates with the Growl notification framework. Popping up a little notification window whenever a test fails… sweet! (Follow the link for instructions on setting this up!)

David Rice

If you need help with the Design, Build, Management, Hosting or Support of your project do get in touch, I'd love to hear from you!

Recently

Archive