Named Test Fixtures
In one of my projects, I have tons of units and functional tests. To speed things up, I set my configuration like this:
test/test_helper.rb
1 class Test::Unit::TestCase 2 self.use_transactional_fixtures = true 3 self.use_instantiated_fixtures = :no_instances 4 end
In my tests, instead of accessing @bob, I now have to do:
test/unit/party_test.rb
1 def test_party_is_destoryed 2 party = Party.find(@parties['bob']['id']) 3 party.destroy 4 assert party.destroyed?, "Party wasn't marked destroyed" 5 end
Works, but isn’t this very verbose ? So, I created myself a little helper::
test/test_helper.rb
1 def party(fixture_name) 2 Party.find(@parties[fixture_name.to_s]['id']) 3 end
All great and dandy. I wanted to share with the community, so I started digging into fixtures.rb to implement it. Much to my surprise, this already exists:
vendor/rails/activerecord/lib/active_record/fixtures.rb
1 class Test::Unit::TestCase #:nodoc: 2 def self.fixtures(*table_names) 3 table_names = table_names.flatten 4 self.fixture_table_names |= table_names 5 require_fixture_classes(table_names) 6 setup_fixture_accessors(table_names) 7 end 8 end
So, I guess I’m going to send a documentation patch instead of code !
UPDATE 1 (Oct 18, 2005): Well, would you look at that, this is all documented in the Class: Fixtures (See the last paragraph under Using Fixtures)
UPDATE 2 (Oct 25, 2005): Rails 0.14.1 is pre-configured like that. In fact, Mike Clark wrote Faster Testing with Rails 1.0 to explain the new behavior.