当需要孩子时,工厂女孩有很多

时间:2015-02-07 14:26:16

标签: ruby-on-rails factory-bot

我有两个模型PostImage。如果没有images,则无法创建帖子。

class Post <  ActiveRecord::Base
  has_many :images 
  validates :images , presence: true
end

class Image <  ActiveRecord::Base
   belongs_to :post
   validates :post_id , presence: true
   validates :name , presence: true
end

现在,我正在为factory girlpost设置image。我和image工厂女孩没关系,但无法设置post工厂女孩应该有图像。

#image
FactoryGirl.define do
  factory :image do
    name "something"
    post_id 121
  end
end

#post 
FactoryGirl.define do
  factory :post do
     title "foo bar"
     after(:create) do |post,evaluator|
      create_list :image , 3 , post: post
     end
  end
end

但我仍然在post images should be present上结束了验证错误。这个错误确实有意义,但如何解决这个问题。

1 个答案:

答案 0 :(得分:1)

这对我有用

FactoryGirl.define do
  factory :post do
     title "foo bar"
     after(:build) do |post,evaluator|
       post.images << (build_list :image , 3 , post: post)
     end
  end
end