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
Subscribe to:
Posts (Atom)