When testing with RSpec etc., data may be prepared in advance with FactoryBot etc., but at that time I will write about how to use Faker that creates random data nicely.
Just install the gem.
Gemfile
group :development, :test do
#(Omitted)
gem 'faker'
end
Terminal
$ bundle install
You can enter Faker :: [genre]. [Title etc.]
in the rb file.
Please check Official Reference to see what is available.
Samples are lined up in the README, so just click on the one you want to use and use it as shown in the link.
It's hard to understand unless you try it, so I'll actually use it.
This time I would like to use Movies. Click Movies in the README to jump to the Movies section on the same page as shown below.
This time we will use Faker :: movie
.
Click Faker :: movie
to jump to the details page.
If you write it exactly as it is written on this page, it will get the data at random.
Let's try to get the movie title with Faker :: Movie.title
.
Check on the console.
Terminal
$ rails c
You will get it like this.
It is interesting because there are data such as Pokemon and Star Wars.
When using FactoryBot, you can write as below.
book.rb
FactoryBot.define do
factory :book do
title { Faker::Book.title }
author { Faker::Book.author }
publisher { Faker::Book.publisher }
end
end
Similarly, if you use a seed file, you can randomly create various initial data.
Recommended Posts