2
3

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.

ActiveHash で定義したデータを FactoryBot の association で用いる

Last updated at Posted at 2018-05-15
class Item < AppliactionRecord
  belongs_to_active_hash :item_detail
end
class ItemDetail < ActiveHash::Base
  include ActiveHash::Associations
  self.data = [
    {id: 1, name: 'Hoge'},
    {id: 2, name: 'Foo'},
  ]
  has_many :items
end

な関連があるとき factory で次のように定義する。

FactoryBot.define do
  factory :item do
    item_detail { ItemDetail.all.sample }
  end 
end

もし以下のように定義してしまうと、 FactoryBot.create(:item) したときに新しい item_detail(id: 3, name: nil) が作成されてしまう。

FactoryBot.define do
  factory :item do
    association :item_detail
  end 
end

Ref: FactoryBot(旧FactoryGirl)で関連データを同時に生成する方法いろいろ

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?