0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails】FactoryBot(Gem)について

Last updated at Posted at 2025-05-06

記事概要

Ruby on RailsのFactoryBot(Gem)について、まとめる

前提

  • Ruby on Railsでアプリケーションを作成している

FactoryBotとは

インスタンスをまとめることができるGem

他のファイルであらかじめ各クラスのインスタンスに定める値を設定しておき、各テストコードで使用する

Gemのインストール手順

Gemfileの記述

手順(設定)

  1. インスタンスの生成を切り出すファイルを作成する
    • FactoryBot導入前に、テストコードを記述するファイルを生成
      1. spec配下に、factoriesフォルダを手動作成
      2. factoriesフォルダに、[モデル名の複数形].rbを手動作成
    • FactoryBot導入後に、テストコードを記述するファイルを生成
      • spec/factories/[モデル名の複数形].rbが自動生成される
  2. 上記で作成したファイルを編集
    • Fakerを使い、ランダム値を入力
      spec/factories/users.rb
      FactoryBot.define do
        factory :user do
          nickname              {Faker::Name.initials(number: 2)}
          email                 {Faker::Internet.email}
          password              {Faker::Internet.password(min_length: 6)}
          # password_confirmationはpasswordと同じ値なので、「password」を指定
          password_confirmation {password}
        end
      end
      
    • 固定値を入力
      spec/factories/users.rb
      FactoryBot.define do
        factory :user do
          nickname              {'test'}
          email                 {'test@example'}
          password              {'000000'}
          # password_confirmationはpasswordと同じ値なので、「password」を指定
          password_confirmation {password}
        end
      end
      

Ruby on Railsまとめ

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?