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

后端 未结 3 1547
无人及你
无人及你 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条回答
  • 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

    0 讨论(0)
  • 2021-02-01 21:40

    The new syntax is:

    before(:create) do |article|
      article.reviewers << FactoryGirl.build(:reviewer, article: article)
    end
    
    0 讨论(0)
  • 2021-02-01 21:42
    factory :article do
      reviewers {|a| [a.association(:reviewer)] }
    end
    

    or

    factory :article do
      before_create do |a|
        FactoryGirl.create(:reviewer, article: a)
      end
    end
    
    0 讨论(0)
提交回复
热议问题