【rspec】FactoryBot サンプルデータの定義の仕方

概要

 テストで使用するサンプルデータの定義の仕方 + 呼び出し方

前提条件

・gemはインストール済み.
rspecを使用する.
・config/application.rb内generatetorの設定欄に、fixtures: falseが記述されていないこと.
・もしくは下のコードの通りにすること.

Bundler.require(*Rails.groups)

module Projects
  class Application < Rails::Application
    config.load_defaults 5.1

    config.generators do |g|
      g.test_framework :rspec,
        # ビュースペックを作成しない.
        view_specs: false,
        # ヘルパーファイル用のスペックを作成しないこと.
        helper_specs: false,
        # ルーティング用のスペックを作成しない.
        routing_specs: false
    end
  end
end

ファイル生成

・文法  $ bin/rails g factory_bot:model モデル名  
・例:  $ bin/rails g factory_bot:model user  

・生成されるファイルの場所.

spec/factories/
├── notes.rb
├── projects.rb
└── users.rb

定義の仕方

・ジェネレーターで作成されたファイルに属性値などを定義する.

FactoryBot.define do
  # aliases: [:owner]はまだわからなくて良い、次回以降の記事で解説
  factory :user, aliases: [:owner] do
    first_name "Aaron"
    last_name  "Sumner"  
    # 呼び出されるたびにnの数が増えていくため、emailがユニークになる.
    sequence(:email) { |n| "tester#{n}@example.com" }
    password "dottle-nouveau-pavilion-tights-furze"
  end
end

・テスト内で呼び出す

   # FactoryBot使用しない場合
   user = User.create(
      first_name: "Joe",
      last_name:  "Tester",
      email:      "joetester@example.com",
      password:   "dottle-nouveau-pavilion-tights-furze",
    )
    # FactoryBot使用する場合
    FactoryBot.create(:user)
    FactoryBot.build(:user)
    # 特定の属性値のみ変更したい場合
    FactoryBot.create(:user, email: nil)
    FaactryBot.build(:user, name: 'foobar')

今日はここまで
作成時間30分 次回以降 関連付け、より複雑なサンプルデータ