Sometimes we need a lots of test data. Most of the times, we use to write test data in fixtures or we may enter the data manually.
For RubyonRails application, there is a better way to add lots of test data. Yes, we can do this with the help of following gems,
sudo gem install populator
sudo gem install faker
To insert the test (dummy) data, you can create the RAKE task or method as following,
#lib/tasks/populate.rake
namespace :db do
desc "Erase and fill database"
task :populate => :environment do
require 'populator'
require 'faker'
User.populate 10 do |user|
user.firstname = Faker::Name.name
user.lastname = Populator.words(1).titleize
user.about_me = Populator.sentences(2..10)
user.email = Faker::Internet.email
user.phone = Faker::PhoneNumber.phone_number
user.street = Faker::Address.street_address
user.city = Faker::Address.city
user.state = Faker::Address.us_state_abbr
user.zip = Faker::Address.zip_code
end
end
end
This will insert mass records into database in quick time. Also we can set up associations,
We will modify above code for User’s association with Club as,
User.populate 10 do |user|
user.firstname = Faker::Name.name
user.lastname = Populator.words(1).titleize
......
user.zip = Faker::Address.zip_code
Club.populate 5 do |club|
club.user_id = user.id
club.name = Populator.words(3..8).titleize
end
end
Once you are done with writing the method, you can run the following RAKE task,
rake db:populate
For more methods, You can refer – http://populator.rubyforge.org/ for POPULATOR gem and http://faker.rubyforge.org/rdoc/ for FAKER gem.
Reference URL – http://railscasts.com/episodes/126-populating-a-database
Thanks,