firstruby

Master ruby with us

Adding lots of test data for RubyonRails application in few seconds

Posted by firstruby on April 26, 2009

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,

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: