How to user factory girl to create associated lists with a has_many with a validation that requires it on create

微笑、不失礼 提交于 2019-12-02 19:13:31

I reposted this over on the Factory Girl github page as an issue and worked my way around to the answer:

before_create do |article|
  article.reviewers << FactoryGirl.build(:reviewer, article: article)
end

The key was doing it in a before_create, so the validations haven't fired yet, and making sure to push the newly created reviewer into the list of reviews on the instance being created. Thanks to Unixmonkey for responding and keeping me trying new things :)

https://github.com/thoughtbot/factory_girl/issues/369#issuecomment-5490908

factory :article do
  reviewers {|a| [a.association(:reviewer)] }
end

or

factory :article do
  before_create do |a|
    FactoryGirl.create(:reviewer, article: a)
  end
end

The new syntax is:

before(:create) do |article|
  article.reviewers << FactoryGirl.build(:reviewer, article: article)
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!