I am trying to populate my rails Test database and am running into issues.
I have a script which I use to rest, generate and populate my Development database which works without issue. Basically something like
namespace :db do
desc "Fill database with sample data"
task populate: :environment do
Rake::Task['db:reset'].invoke
--Create all my dummy data here---
end
end
end
I then run the commands:
bundle exec rake db:populate
bundle exec rake db:test:prepare
The first commands resets and populates my database using the above rake task, but the second command only recreates my data structures and does not populate the data.
I am doing this for some RSPec tests to have access to – but I am wondering if I am approaching this incorrectly? Should I not have ANY test data (only structure) in my test database for TDD? Should everything always run off of Fixtures instead?
In my experience, it’s good practice to not be dependent on running rake tasks or using any other external process to fill in test data. You should do any data loading within the tests themselves and create helpers placed in
spec/supportto avoid duplication where necessary.I’ve seen all kinds of strategies for loading test data: custom seed classes placed in
lib, fixtures (though fixtures can be brittle and a pain in certain cases), and more heavyweight solutions such as the factory_girl_rails and fabrication gems, to name just a few.As for
db:test:prepare, it simply “checks for pending migrations and loads the test schema”, according to the Rails guide; no actual data is loaded.http://guides.rubyonrails.org/testing.html#preparing-your-application-for-testing
Hope that helps!