How (to?) Test Validations, Part 4

This is Part 4 of the preview for the "Keeping Tests Dry" I will be giving at erubycon tomorrow.

One issue with the previous three code examples is that they are testing ActiveRecord. This is unnecessary: ActiveRecord has its own tests, and I already believe that validations work as advertised.

We can use mocks to simply verify that validations are called with the correct arguments. The only tricky thing is that we are mocking class level behavior that happens when the file is read. To avoid dependencies on other tests, we will read the file again in its own module:

  # Gross Trick: reload a model class in a different namespace so we can 
  # set expectations without interfering with load of the "real" class
  class ValidationInteractionTest < Test::Unit::TestCase
    class ValidationInteractionTest::Contact < ActiveRecord::Base; end

    def test_validates_presence_of_gets_called
      model_source = File.join(RAILS_ROOT, "app/models/contact.rb")

What do you think? I would be interested to see the Groovy equivalent.

Get In Touch