I'm attempting to use the new standard way of loading seed data in Rails 2.3.4+, the db:seed
rake task.
I'm loading constant data, which is required for my application to really function correctly.
What's the best way to get the db:seed
task to run before the tests, so the data is pre-populated?
I believe Steve's comment above should be the correct answer. You can use
Rails.application.load_seed
to load seed data into your test envoironment. However, when and how often this data is loaded depends on a few things:Using Minitest
There is no convenient way to run this file once before all tests (see this Github issue). You'll need to load the data once before each test, likely in the setup method of your test files:
Using RSpec
Use RSpec's
before(:all)
method to load seed data for all test for this model:Hope this helps.
Adding
Rake::Task["db:seed"].invoke
to thedb:test:prepare
rake task did not work for me. If I prepared the database withrake db:test:prepare
, and then entered the console within the test environment, all my seeds were there. However, the seeds did not persist between my tests.Adding
load "#{Rails.root}/db/seeds.rb"
to my setup method worked fine, though.I would love to get these seeds to load automatically and persist, but I haven't found a way to do that yet!
The
db:seed
rake task primarily just loads thedb/seeds.rb
script. Therefore just execute that file to load the data.Where to place that depends on what testing framework you are using and whether you want it to be loaded before every test or just once at the beginning. You could put it in a
setup
call or in atest_helper.rb
file.I'd say it should be
Because db:test:load is not executed if you have config.active_record.schema_format = :sql (db:test:clone_structure is)
Putting something like this in lib/tasks/test_seed.rake should invoke the seed task after db:test:load:
For those using seedbank, it changes how seeds are loaded, so you probably can't/don't want to use the
load ...
solution provided here.And just putting
Rake::Task['db:seed'].invoke
into test_helper resulted in:But when we added load_tasks before that, it worked: