Recent Projects

Validating your Fixtures

Here’s a easy way to ensure that you’re using valid data in your fixtures with Rails and Test::Unit:

# test/integration/fixture_validation_test.rb
require 'test_helper'

class FixtureValidationTest < ActionController::IntegrationTest

  test "fixtures should be valid" do
    models = Fixtures.all_loaded_fixtures.keys
    models.each do |model|
      model = model.camelize.singularize.constantize
      fixtures = model.find(:all)
      fixtures.each do |fixture|
        if !fixture.valid?
          puts; puts "WARNING: Invalid fixture: #{fixture.inspect}"
        end
        assert_valid fixture
      end
    end
  end
end

Please feel free to suggest any improvements. Thanks!

6 Responses to “Validating your Fixtures”

  1. Wesley Moxam says:

    We did something similar at Savvica, except it was in the form of a rake task so it could be run on objects in any environment.

    Check it out: http://rails.savvica.com/2008/1/4/rake-models-find_invalid

  2. Nigel Rausch says:

    I believe the capitalize be camelize otherwise multiword models (with underscores) do not convert

  3. Dan Manges says:

    One suggestion: just don’t use fixtures. :-)

  4. Trevor says:

    Thanks for the tip, Nigel – I’ve updated the code to use camelize instead of capitalize.

  5. xuanxu says:

    You can also use the test_fixtures plugin: http://i.justcodeit.net/plugins/test_fixtures/

Leave a Reply