factory girl nested factory

前端 未结 1 1843
陌清茗
陌清茗 2020-12-14 11:39

I have an account model that belongs_to a role model.

factory :role do
  name \"student\"
end

factory :account do
  user
  role
end

The fi

相关标签:
1条回答
  • 2020-12-14 12:19

    If you want a purely FG solution, you could use Traits:

    factory :account do
      user
    
      trait :student do
        association :role, :name => "student"
      end
    
      trait :admin do
        association :role, :name => "admin"
      end
    end
    
    FactoryGirl.create :account, :student
    FactoryGirl.create :account, :admin
    

    However, you can override the properties of the factory when you create the factory object. This allows for more flexibility:

    FactoryGirl.create(:account,
      :role => FactoryGirl.create(:role, :name => "student")
    )
    

    Since this is obviously verbose, I'd create a little helper method:

    def account_as(role, options = {})
      FactoryGirl.create(:account,
        options.merge(:role => FactoryGirl.create(:role, :name => "student"))
      )
    end
    

    Then in your tests:

    let(:account) { account_as "student" }
    

    Alternately, you could just shorten up your role generator so you could use it like:

    def role(role, options = {})
      FactoryGirl.create :role, options.merge(:name => role)
    end
    
    account = FactoryGirl.create :account, :role => role("student")
    
    0 讨论(0)
提交回复
热议问题