has_many while respecting build strategy in factory_girl

后端 未结 3 2077
名媛妹妹
名媛妹妹 2020-12-15 06:22

Situation

# Models
class User < ActiveRecord::Base
  has_many :items 
end 

class Items < ActiveRecord::Base
  belongs_to :user 
  validates_presence         


        
3条回答
  •  萌比男神i
    2020-12-15 06:51

    I usually like to separate building and creating so i can still build the object without going to the database.

    Factory.define(:user_with_items, :parent => :user) do |u|
      u.after_build do |u|
        u.items = (1..2).map {Factory.build(:item, :user => u)}
      end
      u.after_create do |u|
        u.items.each {|i| i.save!}
      end
    end
    

提交回复
热议问题