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
      
  3. FactoryBotが使用できることを確認するために、コンソールを起動する
    % rails c
    
  4. 値を生成し、エラーが発生しないことを確認する
    [1] pry(main)> FactoryBot.create(:user)
      TRANSACTION (0.3ms)  BEGIN
      User Exists? (9.1ms)  SELECT 1 AS one FROM `users` WHERE `users`.`email` = BINARY 'angeles@jones-legros.test' LIMIT 1
      User Create (5.3ms)  INSERT INTO `users` (`name`, `email`, `encrypted_password`, `reset_password_token`, `reset_password_sent_at`, `remember_created_at`, `created_at`, `updated_at`) VALUES ('阿部', 'angeles@jones-legros.test', '$2a$12$2DK1jnXj2cMCDMzvvxToT.UrKCEFSGy0qdPMn0LxdMuN3sfLe7Rqq', NULL, NULL, NULL, '2024-10-02 05:41:18.105810', '2024-10-02 05:41:18.105810')
      TRANSACTION (2.6ms)  COMMIT
    => #<User id: 4, name: "阿部", email: "angeles@jones-legros.test", created_at: "2024-10-02 14:41:18.105810000 +0900", updated_at: "2024-10-02 14:41:18.105810000 +0900">
    
    • インスタンスを保存できない場合、buildで値を確認する
      pry(main)> user = FactoryBot.build(:user)
      
    • エラー「KeyError」が発生
      1. コンソール終了
      2. コンソール再起動
      3. FactoryBotの確認を行う
  5. コンソソールを終了する

まとめ

ダミーデータに画像を添付

テスト用ダミー画像public/images/test_image.pngをインスタンスに付与する

messages.rb
FactoryBot.define do
  factory :message do
    content {Faker::Lorem.sentence}

    after(:build) do |message|
      # io: File.openで設定したパスのファイル(public/images/test_image.png)を、test_image.pngというファイル名で保存
      message.image.attach(io: File.open('public/images/test_image.png'), filename: 'test_image.png')
    end
  end
end

インスタンスに画像が添付できているかを確認する方法

  1. コンソールを起動する
    % rails c
    
  2. 画像が保存できているか確認する
    [1] pry(main)> message = FactoryBot.create(:message)
    #=> 省略
    [2] pry(main)> message.image.attached?
    => true
    

association

インスタンス生成時に、関連する他インスタンスも自動生成される
必ず他モデルの紐付けが必要な場合、こちらの設定が必要

FactoryBot.define do
  factory :tweet do
    text {Faker::Lorem.sentence}
    image {Faker::Lorem.sentence}
    association :user # Userモデルを生成し、インスタンスに紐づける
  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?