3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

FactoryBotでHashに引数を渡す

Last updated at Posted at 2018-02-09

結論

FactoryBot.define do
  factory :user, class: "User" do
    profile {
      {
        name: name,
        age: age,
        nickname: nickname
      }
    }
  end

  transient do
    name Michael
    age 16
    nickname Mike
  end
end

こういうfactoryを作ったら、Spec内で

let(:user) {
  FactoryBot.create(:user, name: 'Robert', nickname: 'Rob')
}

と呼び出す。
transient で定義しているから、userオブジェクトからはnameageは見えない。

let(:user) {
  FactoryBot.create(:user, profile: {
    name: 'Robert', 
    nickname: 'Rob'
  }) 
}

↑ こう書くとageの項目が上書きされて無くなってしまうため困っていたがこの手を思いついたのでメモ

参考

FactoryGirlのtransientとtraitを活用する

3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?