Load Rails Fixtures in Production Mode

Another installment in the “it probably exists elsewhere on the web, but my Google searches weren’t finding it”… how does one take their development database with them into production mode (for performance testing purposes, in our case).

Option 1 – Export Fixtures, database independent. Complicated.
First, run “rake db:extract_fixtures” to make your existing database into a set of YAML files that are saved in your /test/fixtures directory.

Next, copy the .yml files in your /test/fixtures directory into a subdirectory of your /lib folder. We have a folder for rake tasks, which is /lib/tasks, so I copied the fixtures into /lib/tasks/production_fixtures.

Finally, create a task that will import all those fixtures. Part of my reason for writing this blog is in hopes that someday someone will stumble upon it and suggest a better way to accomplish this importing of a directory of fixtures. But until then, you can create a file called “db.rake” in your /lib/tasks folder, then add the following lines to that file:

task :load_fixtures => :environment do
require 'active_record/fixtures'
Fixtures.create_fixtures('lib/tasks/production_fixtures', 'table_name_pluralized')
Fixtures.create_fixtures('lib/tasks/production_fixtures', 'table_name_2_pluralized')

Where “/lib/tasks/production_fixtures” is the directory you put your .yml files in. With this method you need one of these lines for every table, but it works (I just created a list of the files by outputting my directory list into a text file and copying it into the text file).

Finally, run “rake db:load_fixtures RAILS_ENV=production” and you got yourself a populated production database.

TODO: How does this compare to “rake db:fixtures:load”?

Option 2 – Copy MySQL database. Requires MySQL. Simple.
This option is far simpler, but requires MySQL for it to work in the way I’m about to describe. These examples assume that your mysql user is “root”, password is “secret”, and db names are “development_db_name” and “production_db_name”.

To dump your existing database to a file,

mysqldump -u root -psecret development_db_name > db_dump.sql

And to import it into a new database

mysql -u root -psecret production_db_name < db_dump.sql


NOTE: Make sure your development and production databases are on the same migration before trying this stunt.

Leave a Reply

Your email address will not be published. Required fields are marked *