How to seed your rails database with faker for testing

Database schema
gem 'faker'
bundle install
require 'faker'
# generate 20 users
(1..20).each do |id|
User.create!(
id: id, # each user is assigned an id from 1-20
name: Faker::Name.name,
email: Faker::Internet.email,
password: "password", # issue each user the same password
password_confirmation: "password",
role: %w[customer admin agent].sample # a user can have only one of these roles
)
end
role: %w[customer admin agent].sample
# create 10 tickets in DB
(1..10).each do |id|
Ticket.create!(
id: id,
user_id: rand(1..20), # we have userIds between 1 and 20. Assign a ticket to a user randomly
title: Faker::University.name,
status: %w[opened in_progress completed].sample,
request: Faker::Lorem.paragraphs # generate a fake paragraph
)
end
user_id: rand(1..20)
# create comments in DB. Comments belong to tickets
(1..10).each do |id|
Comment.create!(
id: id,
user_id: rand(1..20),
comment: Faker::Lorem.sentence(word_count: 3),
user_name: User.find(rand(1..20)).name,
ticket_id: rand(1..10),
user_role: %w[customer admin agent].sample
)
end
rails db:seed

--

--

--

Growth at Moni(YC W22) | Adebola.dev

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Crash Course — Python & Pandas for Trading and Investing (Part 1)

Dark Matter DeFi Recap March

Double Your Google Colab RAM in 10 Seconds Using a Tiny Line of Code

AWS vs Azure vs Google : The Public Cloud War

FlutterForce — #Week 29

Elegant Way To Verify That Methods Throws Exception In .NET

Then: Woodworker, Now: Junior Full Stack Developer

Install Fluentd on IBM Cloud

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adebola Adeniran

Adebola Adeniran

Growth at Moni(YC W22) | Adebola.dev

More from Medium

RailsTasker: Rails Automated Post Deployment Tasks

Ruby on Rails post deploy task automation

Building a Ruby on Rails API

User Auth and Password Protection: Rails

Drop production database in Rails