Faker
Faker is a Perl's Data::Faker
library. It’s a library that generates fake data like names, addresses, and phone numbers. While developing, Faker can help you generate realistic test data and populate your database with more than a couple of records.
Table of contents
How to install faker
Reminder:
Make sure that your containers are up and running.
In your gemfile, add gem faker
. Given that we will only use faker
for development and test environment, we will put it inside development
and test
group.
gem 'faker'
Then run bundle install.
root@0122:/usr/src/app# bundle install
Fetching gem metadata from https://rubygems.org/..........
Resolving dependencies...
...
Installing faker 3.0.0
Bundle complete! 15 Gemfile dependencies, 67 gems now installed.
Use `bundle info [gemname]` to see where a bundled gem is installed.
Usage
Here are some examples of how Faker can be used:
irb(main):001:0> Faker::Internet.email
=> "sheron.white@gusikowski.net"
irb(main):002:0> Faker::Name.name
=> "Marvin Nitzsche"
irb(main):003:0> Faker::Address.full_address
=> "Suite 872 750 Kassie Well, West Thomasena, SD 17945-2959"
irb(main):004:0> Faker::Lorem.sentence
=> "Unde doloremque sequi magnam."
irb(main):005:0> Faker::Lorem.paragraph
=> "Deserunt fugiat ex. Et at ipsum. Ipsam magnam rerum."
Let’s try and apply it in our seed.
- Create Users
- Create 30 Posts
# db/seeds.rb
- # This file should contain all the record creation needed to seed the database with its default values.
- # The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup).
- #
- # Examples:
- #
- # movies = Movie.create([{ name: "Star Wars" }, { name: "Lord of the Rings" }])
- # Character.create(name: "Luke", movie: movies.first)
+ 10.times do
+ user = User.create!(email: Faker::Internet.email, password: 'qwer4321', password_confirmation: "qwer4321")
+ puts "create user id: #{user.id}, email: #{user.email}"
+ end
+
+ 30.times do |i|
+ puts "start create #{i} post"
+ post = Post.create(title: Faker::Lorem.sentence, content: Faker::Lorem.paragraph, user: User.all.sample)
+ (1..20).to_a.sample.times do
+ Comment.create(content: Faker::Lorem.sentence, user: User.all.sample, post: post)
+ end
+ puts "finish #{i} post"
+ end
Then run the seed on your project.
root@0122:/usr/src/app# rails db:seed
create user id: 1, email: reyna.robel@waters.name
...
create user id: 10, email: dyan.schmidt@walsh.io
start create 0 post
finish 0 post
...
start create 29 post
finish 29 post
Now we already integrated the faker in our application.