views:

426

answers:

2

I have a migration in Rails that inserts a record into the database. The Category model depends on this record. Since RSpec clears the database before each example, this record is lost and furthermore never seems to be created since RSpec does not seem to generate the database from migrations. What is the best way to create/recreate this record in the database? Would it be using before(:all)?

+5  A: 

It's not that RSpec clears the database, it's that Rails's rake:db:prepare task copies the schema (but not the contents) of your dev database into your *_test db.

Yes, you can use before(:all), as transactions are wrapped around each individual example - but a simple fixture file would also do the same job.

(There's a more complicated general solution to this issue: moving to a service-oriented architecture, where your 'dev' and 'test' services are going to be completely separate instances. You can then point your test db config to the development database in your test service, disable rake:db:prepare, and build your test service from migrations as you regenerate it. Then you can test your migrations and data transformations.)

James Baker
+2  A: 

What I like to do is create a folder in db/migration called data, and then put yml fixtures in there, in your case categories.yml

Then I create a migration with the following

def self.up
 down
 directory = File.join( File.dirname(__FILE__), "data" )
 Fixtures.create_fixtures( directory, "categories" )
end

def self.down
  Category.delete_all
end
Jonathan Soeder