为深层嵌套模型创建工厂

时间:2012-11-09 22:36:17

标签: ruby-on-rails testing rspec factory-bot

在我犯罪的那段时间里,我已经使用铁轨已有将近4年了。我从未写过一个单一的测试。不知道为什么我花了很长时间才看到我一直在制造的巨大错误,但我现在已经有了。我想改变我的开发并开始使用TDD。但要做到这一点,我必须为我目前正在开发的应用程序建立一个测试套件。我有rspec和factory_girl设置,我开始理解abit的事情。我有一些相当复杂的模型,我试图测试,我被卡住了。这就是我所拥有的:

class BusinessEntity
  has_many :business_locations

class BusinessLocation
   belongs_to :business_entity
   has_many :business_contacts

   validates :business_entity_id, :presence => true

class BusinessContact
   belongs_to :business_location
   has_many :business_phones

   validates :business_location_id, :presence => true

class BusinessPhone
    belongs_to :business_contact

    validates :business_contact_id, :presence => true

这些模型还有更多,但这是我坚持的。如何为构建所有必需子项的business_entity创建工厂?所以在spec文件中我可以只是FactoryGirl.create(:business_entity)并且能够将它用于其他模型测试。 我有这个工厂

    require 'faker'

FactoryGirl.define do
  factory :business_entity do
    name "DaveHahnDev"        
  end

  factory :business_location do
    name "Main Office"
    business_entity
    address1 "139 fittons road west"
    address2 "a different address"
    city { Faker::Address.city }
    province "Ontario"
    country "Canada"
    postal_code "L3V3V3"
  end

  factory :business_contact do
    first_name { Faker::Name.first_name}
    last_name { Faker::Name.last_name}
    business_location
    email { Faker::Internet.email}
  end

  factory :business_phone do
    name { Faker::PhoneNumber.phone_number}
    business_contact
    number_type "Work"
  end
end

这传递了这个

require 'spec_helper'


  it "has a valid factory" do
    FactoryGirl.build(:business_entity).should be_valid
  end

那么我如何使用这个工厂来创建business_entity,让所有子项用于其他规范测试。

我希望这很清楚,任何帮助都会受到高度赞赏

1 个答案:

答案 0 :(得分:2)

如果我理解正确,你需要创建关联。使用FactoryGirls执行此操作的最基本方法是在另一个工厂块中添加工厂名称。因此,在您的情况下,它将是以下内容:

# factories.rb

FactoryGirl.define do
  factory :business_entity do
    name "DaveHahnDev"        
  end

  factory :business_location do
    business_entity # this automatically creates an association
    name "Main Office"
    business_entity
    address1 "139 fittons road west"
    address2 "a different address"
    city { Faker::Address.city }
    province "Ontario"
    country "Canada"
    postal_code "L3V3V3"
  end

  factory :business_contact do
    business_location
    first_name { Faker::Name.first_name}
    last_name { Faker::Name.last_name}
    business_location
    email { Faker::Internet.email}
  end

  factory :business_phone do
    business_contact
    name { Faker::PhoneNumber.phone_number}
    business_contact
    number_type "Work"
  end
end

添加这些行后,您可以调用FactoryGirl.create(:business_location),它将创建一个新的BussinessLocation记录,BussinessEntity记录并关联它们。

有关详细信息,请查看FactoryGirls Wiki - Associations

相关问题