我已经使用 Rails 将近 4 年了,而在那段时间里我一直在犯罪。我从来没有写过一个测试。不知道为什么我花了这么长时间才看到我一直在犯的巨大错误,但我现在看到了。我想改变我的开发并开始使用 TDD。但要做到这一点,我必须为我目前正在处理的应用程序构建一个测试套件。我已经设置了 rspec 和 factory_girl,并且开始有点理解了。我有一些相当复杂的模型正在尝试测试,但我被卡住了。这是我所拥有的:
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 创建一个工厂来构建所有需要的 child ?因此,在规范文件中,我可以只使用 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 以用于其他规范测试。
我希望这已经足够清楚了,我们将不胜感激
最佳答案
如果我没理解错的话,您需要创建关联。使用 FactoryGirls 执行此操作的最基本方法是在另一个工厂 block 中添加工厂名称。因此,在您的情况下,它将是以下内容:
# 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
关于ruby-on-rails - 为深层嵌套模型创建工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13317041/