Faker It So You Can Make It

It’s common knowledge that any database that you create is intended to have data in it. When testing out one or two tables in a database, it may be easy to just hard-code some entries. For example, if we want to create an app or website that is based around the DreamWorks series How to Train Your Dragon, we should create some dragons and some characters, like so:

We can easily take some time and create some simple objects. But let’s say our app/website requires us to have 20 of each of those objects. But what if it requires 20 saddle types, islands to explore, dragon snacks, and dragon species as well? The thought of taking the time to hard-code each of those groups of objects makes my head hurt.

Luckily, that’s where Faker comes into play. By design, Faker is a port of Perl’s Data::Faker library that generates fake data. We can use faker to generate fake data for us, and save time on worrying about creating those objects on our own. Not only that but Faker offers a huge amount options to fake, from Addresses to TV Shows, Anime to Chuck Norris.


Faker needs to be installed in the Gemfile with the following command:

gem install faker


Installing is not enough, however. You also need to require the use of faker in your program with the following line:

require ‘faker’

From here you are good to go! Start generating fake data to flesh out your program for testing!

Getting back to the How to Train Your Dragon example, let’s generate some dragons.

These five lines of code produce 20 different dragon names for us. All we have to do is loop over creating a new dragon object, set the name equal to the Faker options, and save that object into the database. With some other Faker options you can get even more complex with the fake data you produce. Using a vehicle example, you can fake 26 different attributes about the vehicle including the make, model, color, VIN and millage of the vehicle. In this case, I chose How to Train Your Dragon because I loved the movies and score to the movies.

Hopping over to our index page for those generated dragons and we can see:

A nice list of our perfectly random dragon names! Now one thing to note is that Faker does not inherently make the random data unique, but that can be rectified by placing a .unique before the attribute you are faking, and after the object you are faking like so:

With that, you can start faking your way through easy data creation! I hope you found this tutorial helpful and if you need any further explanation, you can find it at the Faker Github!