Wednesday, November 18, 2009

Load default lookup data with Rails fixture



The Rails Fixture is a great feature to load sample test data before running unit, functional or integration tests. While it is mostly used in loading test data, it can be a handy tool to load default lookup data for the staging or production database. We can use the “create_fixtures” class method of “Fixture” class.

The following code snippet loads the data from the “countries.yml” file into the “countries” table.

require 'active_record/fixtures'

class CountryData
 def load()
   fixtures_folder = File.join(RAILS_ROOT, 'test', 'fixtures')
   fixtures.create_fixtures(fixtures_folder , " countries " )
 end
end


In this case,the “countries.yml” file must be present in the “<RAILS_ROOT>\test\fixtures” folder.

If we need to load data from all the “.yml” files of a particular folder and don’t want to hard code the names of the individual files as the above code snippet, the following code will do.

require 'active_record/fixtures'

class LoadDefaultData
 def load()
   fixt_folder = File.join(RAILS_ROOT, 'test', 'fixtures')
   fixtures = Dir[File.join( fixt_folder, '*.yml')].map {|f|
   File.basename(f, '.yml') }
   Fixtures.create_fixtures(fixt_folder, fixtures)
 end
end

2 comments:

Sohan said...

I liked your post. However, if you are looking into insert seed data, such as application start-up data, Rails 2.3.4 has an elegant solution for you. Please see this railscast at http://railscasts.com/episodes/179-seed-data

However, for previous versions of Rails, you can use Seed-fu plugin to do this for you.

Arif said...

Thanks for the suggestions.The blog post is a quick and easy way to manually load the fixture data for preparing the test environment.
I will surely look at the techniques you have suggested.