Tech - November 2006 Archives

Metaprogramming Unit Tests

Here's how a lot of my tests look right after I've created my model. I got this pattern from Rick Olson's restful_authentication generator plugin.

require File.dirname(__FILE__) + '/../test_helper'
class EventTest < Test::Unit::TestCase
  fixtures :events

  def test_should_create_event
    assert_difference Event, :count do
      event = create_event
      assert !event.new_record?, "#{event.errors.full_messages.to_sentence}"
    end
  end

  def create_event(options={})
    Event.create({:name => "Test Event", :date => 1.week.from_now }.merge(options))
  end
end

It's a nice clear pattern, but I inevitably make typing errors, especially in the creation method. This problem is exacerbated when I'm writing essentially the same test for tons of different models. Here's how I'd love it to look: