How to set up factory in FactoryGirl with has_many association

前端 未结 5 769
深忆病人
深忆病人 2020-12-07 12:54

Can someone tell me if I\'m just going about the setup the wrong way?

I have the following models that have has_many.through associations:

class List         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-07 13:42

    You could use trait:

    FactoryGirl.define do
      factory :listing do
        ...
    
        trait :with_features do
          features { build_list :feature, 3 }
        end
      end
    end
    

    With callback, if you need DB creation:

    ...
    
    trait :with_features do
      after(:create) do |listing|
        create_list(:feature, 3, listing: listing)
      end
    end
    

    Use in your specs like this:

    let(:listing) { create(:listing, :with_features) }
    

    This will remove duplication in your factories and be more reusable.

    https://robots.thoughtbot.com/remove-duplication-with-factorygirls-traits

提交回复
热议问题