使用 FactoryGirl 使用单个工厂构建多个对象
build multiple objects with a single factory with FactoryGirl
是否可以让工厂不关联到特定的 ActiveRecord 模型?相反:工厂的唯一目的是构建一堆 other 对象:
# test/factories/address_options.rb
FactoryGirl.define do
factory :address_option do
trait :create_them do
after(:create) do
create(:state)
county = create(:county)
create(:city, county: county)
create(:zip_code)
end
end
end
end
例如:所需用法为:create(:address_option, :create_them)
这当然行不通,因为没有AddressOption
class,更不用说address_options
table了。我得到的错误是:
NameError: uninitialized constant AddressOption
我知道我可以简单地在与真实 activerecord 对象关联的工厂之一上创建一个 trait
。但这有点不同,因为我正在创建一种 "aggregate" 工厂:一个创建一堆对象的工厂,其中一些对象相互关联,而另一些对象没有关联,但所有对象仍然相关。
基于评论中建议的工作解决方案。我不确定这是否被认为 "best practice" 用于使用工厂,但它至少是表示抽象 "aggregate" 工厂的有效解决方案:
# test/factories/aggregates/address_option.rb
class AddressOption
include FactoryGirl::Syntax::Methods
def create_them
create(:state)
county = create(:county)
create(:city, county: county)
create(:zip_code)
end
end
用法:AddressOption.new.create_them
是否可以让工厂不关联到特定的 ActiveRecord 模型?相反:工厂的唯一目的是构建一堆 other 对象:
# test/factories/address_options.rb
FactoryGirl.define do
factory :address_option do
trait :create_them do
after(:create) do
create(:state)
county = create(:county)
create(:city, county: county)
create(:zip_code)
end
end
end
end
例如:所需用法为:create(:address_option, :create_them)
这当然行不通,因为没有AddressOption
class,更不用说address_options
table了。我得到的错误是:
NameError: uninitialized constant AddressOption
我知道我可以简单地在与真实 activerecord 对象关联的工厂之一上创建一个 trait
。但这有点不同,因为我正在创建一种 "aggregate" 工厂:一个创建一堆对象的工厂,其中一些对象相互关联,而另一些对象没有关联,但所有对象仍然相关。
基于评论中建议的工作解决方案。我不确定这是否被认为 "best practice" 用于使用工厂,但它至少是表示抽象 "aggregate" 工厂的有效解决方案:
# test/factories/aggregates/address_option.rb
class AddressOption
include FactoryGirl::Syntax::Methods
def create_them
create(:state)
county = create(:county)
create(:city, county: county)
create(:zip_code)
end
end
用法:AddressOption.new.create_them