I need to fill the test development database with data, for example from factorygirl
, but I'd like to use it from rails console.
How I put example data in db so I can fetch it from console and do some test there?
Faker is also a good solution.
Here's how my lib/tasks/sample_data.rake
looks like. I run it with rake db:populate
.
Creates 50 entries with random info.
require 'faker'
namespace :db do
desc "Fill database with sample data"
task :populate => :environment do
Rake::Task['db:reset'].invoke
50.times do |n|
name = Faker::Company.name
year = 1900+rand(111)
rating = 1+rand(10)
watched = (1 == rand(2) ? true : false)
imdb_id = rand(1000000)
Movie.create!(:name => name,
:year => year,
:rating => rating,
:watched => watched,
:imdb_id => imdb_id)
end
end
end
I've made a gem test_dummy that works like Factory Girl to define lots of fake data. When properly configured you can do things like this:
# Create 100 fake companies
100.times { Company.create_dummy }
# Create a single fake company on-demand
fake_company = Company.create_dummy
The alternative is to use the db/seeds.rb
facility or to load in your fixtures into your development environment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With