0

I want to specify following type of associations through FactoryGirl. I have three models A, B and C where model of C which is in DataMapper is as follows:

Class C do
   include DataMapper::Resource
   belongs_to :A, :key=>true
   belongs_to :B, :key=>true
end

I don't know how to specify this in FactoryGirl i.e. what I mean is I want to write like this:

factory :c do |c|
<To be Filled>
end

Please help.

4

3 回答 3

0
FactoryGirl.define do
  factory :c do |f|
    f.a
    f.b
  end
end

如果您为两者创建工厂a并且b确保工厂的名称与模型的名称相同,那么您需要指定关联。FactoryGirl 将在您每次执行以下操作a时创建: . 关联应仅在一侧指定,最好是所属的一侧。bFactoryGirl.create(:c)

于 2013-08-22T13:09:30.077 回答
0

许可证属于 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' 块初始化需要在保存对象之前初始化的值。

于 2013-08-22T13:06:43.207 回答
0

不确定DataMapper(以及它如何适合/是否包含在工厂定义中)但对于关联,请执行以下操作:

FactoryGirl.define do

  factory :C do |c|
    ...
    c.association :a
    c.association :b
  end  

end
于 2013-08-22T13:07:03.177 回答