FactoryGirl build_stubbed strategy with a has_many association

前端 未结 3 1402
情话喂你
情话喂你 2020-12-12 13:46

Given a standard has_many relationship between two objects. For a simple example, let\'s go with:

class Order < ActiveRecord::Base
  has_many :line_items
         


        
3条回答
  •  悲&欢浪女
    2020-12-12 14:18

    I've seen this answer floating around, but ran into the same problem you had: FactoryGirl: Populate a has many relation preserving build strategy

    The cleanest way that I've found is to explicitly stub out the association calls as well.

    require 'rspec/mocks/standalone'
    
    FactoryGirl.define do
      factory :order do
        ignore do
          line_items_count 1
        end
    
        after(:stub) do |order, evaluator|
          order.stub(line_items).and_return(FactoryGirl.build_stubbed_list(:line_item, evaluator.line_items_count, :order => order))
        end
      end
    end
    

    Hope that helps!

提交回复
热议问题