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

后端 未结 3 1548
无人及你
无人及你 2021-02-01 20:45

In a Rails application, given three models User, Article and Reviewer with the following relationships and validations:

class User < ActiveRecord::Base
  has_         


        
3条回答
  •  -上瘾入骨i
    2021-02-01 21:33

    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

提交回复
热议问题