load_and_test_fixtures
When writing tests for Ruby on Rails we use fixtures to fill up our database. Most of the time this is a great approach, but sometimes we lose a lot of time debugging a problem that happens when you have invalid fixtures. To avoid this in the future, I’ve written a small test-helper to replace the “fixtures” command in your tests:
in test_helper.rb:
class Test::Unit::TestCase def self.load_and_test_fixtures *args self.fixtures *args args.each do |klass| class_eval <<-FUNC def test_1st_#{klass.to_s}_fixtures #{klass.to_s.classify.constantize}.find(:all).each do |inst| assert inst.valid?, inst.inspect + " - Validation error: " + inst.errors.full_messages.to_s end end FUNC end end
In your test this gets you:
class UserTest < Test::Unit::TestCase load_and_test_fixtures :users def test_valid assert true end end
and then, with valid tests:
Loaded suite /Users/jan/Projects/Openminds/sock/test/unit/user_test Started .. Finished in 0.133788 seconds. 2 tests, 11 assertions, 0 failures, 0 errors
and with a bad fixture you get:
Loaded suite /Users/jan/Projects/Openminds/sock/test/unit/user_test Started F. Finished in 0.148564 seconds. 1) Failure: test_1st_users_fixtures(UserTest) method test_1st_users_fixtures in (eval) at line 3 method each in (eval) at line 2 method test_1st_users_fixtures in (eval) at line 2 #<NormalUser id: 940844698, name: "Normal User 1", status: "active", type: "NormalUser", parent_id: 344941680> - Validation error: Name has already been taken. <false> is not true. 2 tests, 10 assertions, 1 failures, 0 errors
Comments
-
I'm currently looking at http://replacefixtures.rubyforge.org/, it's a not as fast as the regular fixtures (although this isn't really a problem for me) but it does address the problem you just described.