How to install and configure the Faker gem to create data for a Ruby on Rails application

How to install and configure the Faker gem to create data for a Ruby on Rails application

Faker Gem

The Faker gem is a popular Ruby library used for generating fake or random data. It's particularly helpful in development and testing environments where you need placeholder data to simulate real-world scenarios without using actual sensitive or confidential information.


Add the gem to the Gemfile

Initial code

# Gemfile
gem 'faker'

Complete code

source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby '2.7.4'

gem 'devise'
gem 'rails', '~> 6.1.7', '>= 6.1.7.4'
gem 'pg', '~> 1.1'
gem 'puma', '~> 5.0'
gem 'sass-rails', '>= 6'
gem 'webpacker', '~> 5.0'
gem 'turbolinks', '~> 5'
gem 'jbuilder', '~> 2.7'
gem 'simple_form'
gem 'faker'
gem 'bootsnap', '>= 1.4.4', require: false

group :development, :test do
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end

group :development do
  gem 'web-console', '>= 4.1.0'
  gem 'rack-mini-profiler', '~> 2.0'
  gem 'listen', '~> 3.3'
  gem 'spring'
end

gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]


Install the gem and its dependencies

Command

In your terminal emulator:

bundle install

Output

Check installation

In your terminal emulator:

bundle info faker


Meet the generators

Through the website

  1. Go to the website;

  2. Go to Generators, which is in Table of Contents;

Check generators


Implement seeds file

# db/seeds.rb
30.times do
  Course.create!([{
    title: Faker::Educator.course_name,
    description: Faker::TvShows::GameOfThrones.quote,
    user_id: 1
  }])
end


Run seeds file

In your terminal emulator:

rails db:seeds

Output


Test it


Celebrate

You've made it!

The Office GIF - The Office Happy - Discover & Share GIFs


Let's become friends


Final thoughts

I hope this article has been helpful to you. Please feel free to reach out if you have any questions. Your thoughts, suggestions, and corrections are more than welcome.

By the way, don't hesitate to drop your suggestions for new blog articles.

I look forward to seeing you next time.