DEV Community

nadia4206
nadia4206

Posted on

πŸ’Ž How to use the Ruby Faker Gem πŸ’Ž

What is the Ruby Faker Gem? It's a handy little tool that allows you to be able to easily create as much dummy data as you need to test out your methods. You can use this blog as a beginners guide to using Faker!

To start, add the faker gem to your project by running "gem install faker" in your project terminal.

Image description

Be sure to check that your Gemfile has a line for the faker gem (i.e. gem "faker"). If it doesn't, be sure to add it.

Image description

Add "require 'faker'" to the top of your seeds.rb file:

Image description

From here, you can use the handy dandy faker documentation to guide you through creating your data.

Here's how I set up data using Faker for a table called "Chefs":

In my Chefs table, I have 3 fields: first_name, last_name, and current_restaurant.

To get a Faker generated first_name, I checked the documentation, found the "Name" category, and saw there was an option to generate a first name: Faker::Name.first_name. You can do pretty much the same thing to generate a last name by using: Faker:: Name.last_name.

Finally, for current_restaurant I searched the documentation and found there is a Faker category for Restaurant! I go ahead and use Faker::Restaurant.name for the current_restaurant field:

Image description

From here, you can seed your data like you normally would (rake db:seed). Once your data is done seeding, you'll see randomly generated first names, last names, and current restaurants in your database:

Image description

Pretty nifty!

Top comments (0)