[Ruby] [Rails] Prepare dummy data for testing [Faker]

1 minute read

Introduction

When testing with RSpec etc., we may prepare data in advance with FactoryBot etc., but at that time, I will write about how to use Faker which makes random data nicely.

Preparation

Just install the gem.

Gemfile


group :development, :test do
  # (Omitted)
  gem'faker'
end

terminal


$ bundle install

How to use

Enter Faker::[genre].[title, etc.] in the rb file. Please check Official Reference to see what is available.

There are samples lined up in the README, so just click the one you want to use and follow the link. 278199070c4abe565b7f1ecb13ca831c.png

It is difficult to understand unless you try it, so I will try it. This time I would like to use Movies. Click Movies in README to jump to the Movies column on the same page as shown below. 25cbc0c934fbfedd13009afd6e7fb9ff.png This time, use Faker::movie. Click on Faker::movie to jump to the details page. 9c862c81313fa7018403ab0fb7212a8e.png If you describe it exactly as it is written on this page, it will randomly acquire data. Let’s get the movie title with Faker::Movie.title.

Check in the console.

terminal


$ rails c

95008ab8d5f596fb880f99867f2cab20.png

You will get it like this.

It’s interesting because there are data such as Pokemon and Star Wars. 3b3af87aaeeec64d399f9f9819055435.png b03d65bc4ae23c1a32f8c04b8bf6266e.png

How to use FacrotyBot

When using FactoryBot, it is OK to write as follows.

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.