Validating your Fixtures
September 20th, 2008 by TrevorHere'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!
Nice one.
For comparison: http://blog.hasmanythrough.com/2006/8/27/validate-all-your-records
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
I believe the capitalize be camelize otherwise multiword models (with underscores) do not convert
One suggestion: just don’t use fixtures. :-)
Thanks for the tip, Nigel - I’ve updated the code to use camelize instead of capitalize.
You can also use the test_fixtures plugin: http://i.justcodeit.net/plugins/test_fixtures/