【问题标题】:Specifying Associations in Factory在工厂中指定关联
【发布时间】:2013-08-22 12:57:00
【问题描述】:
我想通过 FactoryGirl 指定以下类型的关联。我有三个模型 A、B 和 C,其中 DataMapper 中的 C 模型如下:
Class C do
include DataMapper::Resource
belongs_to :A, :key=>true
belongs_to :B, :key=>true
end
我不知道如何在 FactoryGirl 中指定它,即我的意思是我想这样写:
factory :c do |c|
<To be Filled>
end
请帮忙。
【问题讨论】:
标签:
ruby-on-rails
rspec
factory-bot
ruby-datamapper
【解决方案1】:
不确定DataMapper(以及它如何适合/是否包含在工厂定义中)但对于关联,请执行以下操作:
FactoryGirl.define do
factory :C do |c|
...
c.association :a
c.association :b
end
end
【解决方案2】:
许可证属于 LicenseTemplate
FactoryGirl.define do
factory :license do
start_date { Time.now}
end_date { Time.now + 30.days }
factory :license_with_template do
association :license_template, factory: :license_template
end
after(:build) do |doc|
if doc.license_template
doc.agents_count = doc.license_template.agents
doc.requests = doc.license_template.requests
end
end
end
end
上面的代码给了我两个工厂'license'和'license_with_template'。 after 'build' 块初始化需要在保存对象之前初始化的值。
【解决方案3】:
FactoryGirl.define do
factory :c do |f|
f.a
f.b
end
end
如果您为a 和b 创建工厂,并确保工厂的名称与模型的名称相同,那么您只需要指定关联。每次您这样做时,FactoryGirl 都会同时创建 a 和 b:FactoryGirl.create(:c)。关联应仅在一侧指定,最好是所属的一侧。