Import fixutres into database

It turns out that the work-around suggested below is completely redundant. It's a case of RTFM. See Quick tips about using rake to manage your database schema and fixture data for a concise guide to using rake for importing fixtures into a database.

Today I have been looking for a way to import Rails fixtures (yaml files) into a database. I would have used this plugin - Dump or Slurp YAML Reference Data (and Fixtures) - but the command to read the fixture back into the database doesn't work with Ruby 1.8.5 / Rails 1.1.6.

The idea

Instead I've applied a simple work-around that exploits the fact that the Rails testing framework will read the fixtures and populate the test database until a test completes. A dummy test that waits for user input is all that's required to populate the test database, at which point you can issue a single command-line database command to copy the database.

I wait for user input because I'm not sure whether the test teardown will clear the test database or not. If not, then the test_dummy method doesn't have to do anything!

The code

Create a file in the db directory, called populate_db.rb, containing the following code:

require File.dirname(__FILE__) + '/../test/test_helper'

class DummyTestToPopulateDB < Test::Unit::TestCase
  fixtures :accounts
  
  def test_dummy
    puts 'Copied the test database (y/n)? '
    begin
      answer = gets
      answer.chomp!
    end until answer == 'y'
  end
  
end

Change the list of fixtures to whatever fixtures you want in the database. e.g. fixtures :categories, :products, :categories_products.

Of course the file can go anywhere and be called whatever you'd like, but make sure you change the path of the require statement if you place it somewhere else.

Usage

Run the test with ruby db/populate_db.rb then, as it waits for you to type y, copy the test database to wherever you'd like. For example, to copy the (mysql) test database to the development database you could issue the following mysql command:

mysqldump -u[username] [appname]_test | mysql -u[username] [appname]_development

Last modified: 26/04/2007 Tags: (none)

This website is a personal resource. Nothing here is guaranteed correct or complete, so use at your own risk and try not to delete the Internet. -Stephan

Site Info

Privacy policy

Go to top