[Rails] Prepare dummy data to be used for testing [Faker]

Introduction

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.

Preparation

Just install the gem.

Gemfile


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

Terminal


$ bundle install

How to use

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. 278199070c4abe565b7f1ecb13ca831c.png

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. 25cbc0c934fbfedd13009afd6e7fb9ff.png This time we will use Faker :: movie. Click Faker :: movie to jump to the details page. 9c862c81313fa7018403ab0fb7212a8e.png 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
95008ab8d5f596fb880f99867f2cab20.png

You will get it like this.

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

How to use with FacrotyBot

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

[Rails] Prepare dummy data to be used for testing [Faker]
Generate dummy data for various tests with Faker (java)
[RubyOnRails] What kind of data should active_hash be used for?
Options for rails new and settings to be done after rails new
[Rails] Various ways to delete data
[Rails 6] cocoon_ Add id and data attributes to the form to be added
Create realistic dummy data with gem Faker
Prepare the security check environment for Rails 6
[Rails] Manage data for each seed file
Testing for Error Messages: Rails Tutorial Notes-Chapter 7
[Rails] Get standard input for multi-line data
[Rails] How to handle data using enum
[Android] I want to create a ViewPager that can be used for tutorials