Using Faker Gem To Seed Your Application

Michael Jester
2 min readJun 16, 2020

--

Some of the most time-consuming parts of creating a Ruby application is trying to seed your database. I mean seriously, can anyone think of 100 movies off the top of their head? (If you can, you’re awesome and congrats.)

Film.create(:title => "The Shawshank Redemption")
Film.create(:title => "The GodFather")
Film.create(:title => "Forrest Gump")

Okay, I’m stopping after three. Even if you can think of your test data, the amount of time it will take to code it all out can add up, and one mistake can have to scratching your head for a long time. There has to be a better way, right?

Yes! Yes there is. Here comes the Faker gem. Those 100 movies can be simplified to just three lines of code.

100.times do
Film.create(:title => Faker::Movie.uniq.title)
end

Quick note

Faker generates data at random. Therefore, every time you call a method on its library of data, a different result will happen. So, if you have to seed you database more than once, you probably won’t get the same data again. And if you generate too much there is a possibility of getting duplicates.

You can have .uniq to your Faker code to prevent the duplicates from happening, but you might get an error if you try to generate too many unique records.

List of Faker’s Generators

And it’s not just movies. Faker has everything to names, tv shows, address, video games, and more. Here’s a screen capture as of June 17 of the high-level features they have:

More complex example

If you wanted to get more complex than the film example above, you could do something like the code below:

100.times do
User.create(
full_name: Faker::Name.name,
date_of_birth: Faker::Date.birthday(min_age: 21, max_age: 65),
email: Faker::Internet.email,
occupation: Faker::Job.title,
favorite_basketball_team: Faker::Sports::Basketball.team
)
end

And this is fast, too. I timed this code at different intervals, and the results are below:

+-----------+------------+
| records | time |
+-----------+------------+
| 100 | 0.91s |
| 1,000 | 1.19s |
| 10,000 | 4.37s |
| 100,000 | 42.48s |
+-----------+------------+

Changing your location

Not all names, zip codes, address, etc. are formatted the same. That’s why another good feature for the Faker gem is you can change your location. You can read more at the docs, but faker allows you to change the locale.

# Sets the locale to "Simplified Chinese":
Faker::Config.locale = 'zh-CN'

TLDR

To TL:DR this, unless you can think and code 100,000 records with information in less than a minute, you should probably look into the Faker gem when seeding your database.

--

--