[Ruby] I want to randomly generate information when writing test code

2 minute read


1. Conclusion

2.Introduction method

3. How to write a nickname, email, and password

4. Another way of writing

Supplement: How to write the date/surname and name (kanji and katakana)

  1. Conclusion

    Describe gem “faker” in gemfile and bundle install. Then, create a facroies folder in the spec folder, create the file you want to describe, and program it.

  2. Introduction method

    *Here, we will omit the introduction of gem “rspec-rails” and gem “factory_bot_rails”! I will assume that you have bundle installed both of them. If you post an article about “Rspec” or “FactoryBot”, we’ll put a link here too!
    Step ❶

gemfile folder

group :development, :test do




Step ❷


% Bundle install

Write in terminal like this:

Step ❸ Create a factories folder in the spec folder, Create any file. (“Model name.rb” for Ruby)
Step ❹

FactoryBot.define do
  factory :user do
- ------ It will be described below from here ------------


  1. How to write nickname and email
"----- Starting from here --------"

In the column

nickname {Faker::Name.name}
email {Faker::Internet.free_email}

You can randomly generate by writing! nickname and email will have the same name as the DB column.

  1. How to write a password
password = Faker::Internet.password(min_length: 6)
password {password}
password_confirmation {password}

min_length:6 matches the intrinsic validation of gem “devise”. Also, the “confirmation password” to enter twice is described.

  1. How to check if it is generated

    At the terminal


%rails c

And then open the console


pry(main)>FactoryBot.create(:model name)

*pry is because we are introducing binding.pry.

If you enter as below, you can see that the information of nickname and email is randomly generated! *Password is encrypted by encrypted_password.


nickname: "Sen. Lou Schimmel", email: "[email protected]"

  1. Another way of writing

    If it is a pattern that does not introduce gem “faker”, You can also write like this!

FactoryBot.define do
  factory :user do

  nickname {"taro"}
  email {"[email protected]"}

Supplement. How to write date/surname and name (kanji and katakana)

From the conclusion,

FactoryBot.define do
  factory :user do
    transient do
      person {Gimei.name}
   date {Faker::Date.backward}
   first_name {person.first.kanji}
   last_name {person.last.kanji}
   first_name_kana {person.first.katakana}
   last_name_kana {person.last.katakana}

Write like this. However, there is one thing I want you to note. Since it is not possible to randomly generate kanji or katakana (kana) in gem “faker”, add gem “gimei” to the gemfile and perform bandle install.


transient do
person {Gimei.name}

This way you can use the gem freely.

When actually using Put “person.” Can be specified by last name and first name (“first”/”last”), It can be specified by kanji and katakana (“kanji”/”katakana”).