Validating your Fixtures

September 20th, 2008 by Trevor

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!

Comments

Posting code? Please use Pastie.

Have a question? Please visit the Forum.

6 Comments

  1. Nice one.

    For comparison: http://blog.hasmanythrough.com/2006/8/27/validate-all-your-records


  2. 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


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

    Comment by Nigel Rausch on September 20, 2008

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


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

    Comment by Trevor on September 21, 2008

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

    Comment by xuanxu on September 22, 2008