Lets Use Faker to Generate Seed Data

Gregory Diaz
3 min readFeb 11, 2020

--

If you have ever wanted to populate some seed data quickly and effectively without manually typing each and every one, there’s a gem called Faker to make your life easier. I’ll go over how to get started and which generators should be your go-to for quick and easy seed data creation.

First thing’s first, install the Faker gem by typing “gem install faker” into your terminal and bundle install.

gem install faker && bundle install 

If all goes well, your gem file should look like this:

Once that’s all taken care of, you will have the Faker gem at your disposal.

So let us say we have our tables ready and already migrated. We now want to populate our seed.rb file. We could initialize a new instance of our classes one by one but no one has time for that. Let’s use our Faker gem to make our lives easier and save our precious time.

The following is how I used Faker to generate my seed data. For example, I wanted names for my users. I used the Faker::Name generator to make a random collection of names. Given the random nature of the generation, there is a chance you may have repeat values. You ought to prefix your method call with unique to ensure unique values. This should return a unique name every time it is called.

Let’s say your User class has a number of attributes you couldn’t possibly want to fill out yourself. Use Faker. Here’s an example:

You should become familiar with all of the generators here. Click on the class and method of your choosing and follow the syntax.

Some of the more useful generators I’ve used are:

From here, we’re going to want to run db:seed in our terminal. Check your console and we should have new instances.

This is what I got for my Reviews, my personal favorite is the Faker::TvShows::RuPaul.quote generator for comments.

Practice using Faker. It’s a time saving tool to have in your arsenal of gems. If you can take the time to learn it, your initial investment will return many fold. It’s what you learn from doing, is the best teacher of all. Enjoy, and thank you for reading.

Resources:

https://rubygems.org/gems/faker

https://github.com/faker-ruby/faker

--

--