LoginSignup
8
8

More than 3 years have passed since last update.

FactoryBot の使い方

Last updated at Posted at 2019-08-08

FactoryBot の使い方

spec/factories/users.rb に記述していこう。

spec/factories/users.rbの全貌

spec/factories/users.rb
FactoryBot.define do
  factory :user do #詳細データが必要ないときは、user だけ作成する
    _account = Faker::Internet.username #データの重複が起きないように数字が1ずつ増えてaccountが生成される。

    name { Faker::Name.name }
    sequence(:account) { |n| "#{n}_#{_account}" } #数字を1ずつ増やすための処理
    sequence(:email) { |n| Faker::Internet.email("#{n}_#{_account}") } #数字を1ずつ増やすための処理

    trait :with_user_detail do #詳細データも必要なときは、user_detail も一緒に作成する
      user_detail #association :user_detail, factory: :user_detail の省略形
    end
  end
end


# 生成する時のコマンド
# user = FactoryBot.create(:user) userデータのみ

# user = FactoryBot.create(:user, :with_user_detail) user_detailsもセットで

Faker gem をうまく組み合わせることで、FactoryBot でランダムなデータを作ることができる

FactoryBot の使い方

FactoryBot.create

FactoryBot を使ってレコードを作成します。(newからsaveまでやっちゃうって事)

# FactoryBot を使う場合
FactoryBot.create(:user)

# 省略形が一般的
create(:user)

# FactoryBot を使わない場合
User.create!(name: "chinju", account: "chinju", email: "chinju@example.com")

FactoryBot.build

FactoryBot を使って、インスタンスを new します。

# FactoryBot を使う場合
FactoryBot.build(:user)

# 省略形が一般的
build(:user)

# FactoryBot を使わない場合
User.new(name: "chinju", account: "chinju", email: "chinju@example.com")

FactoryBot.attributes_for

FactoryBot の定義から、値を Hash 形式で受け取ります。

# FactoryBot を使う場合
FactoryBot.attribute_for(:user)

# 省略形が一般的
attributes_for(:user)

# FactoryBot を使わない場合
{ name: "chinju", account: "chinju", email: "chinju@example.com" }

ランダムではなく任意で値を設定したい時

# name をねこくんで上書き 
FactoryBot.build(:user, name: "ねこくん")

# name に値をいれない
FactoryBot.build(:user, name: nil)

テストで活用しよう!!

8
8
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
8
8