2013-10-14 36 views
2

基本上是:FactoryGirl +祖先有两个层次深

  • 我有有许多Subjects一个Structure模型。
  • 每个主题都有一个父级,并且可以是2级深度。
  • 一个Structure必须有一个主题at_depth 0和一个主题at_depth 2.

问题:

  • 我无法弄清楚如何建立我的主题厂和如何使协会在结构工厂。

我在轨道4,factory_girl_rails 4.2.1和2.0.0的Ruby

这里是我试图为主体的工厂:

factory :subject_grand_parent do |f| 
    name Forgery(:name).company_name 

    factory :subject_parent do |s| 
    f.parent { Factory.create(:subject_grand_parent) } 

    factory :subject do |s| 
     f.parent { Factory.create(:subject_parent) } 
    end 
    end 
end 

但我不能定义父两次。

而在Structure工厂,我不确定如何为我的关联定义多个主题。这里 我有什么现在:

factory :structure do 
    subjects {|structure| [structure.association(:subject)] } 
    ... 
end 

在此先感谢

回答

2

你有没有考虑使用后(:编译)块?

+0

怎么想不到呢!这工作。但是,我如何将多个主题分配给我的结构工厂? (:build)do | structure |后的 –

+1

2.times {structure.subject << build(:subject,structure:structure)} end –

2

好吧,这似乎工作:

Subject厂:

厂:主题做 名伪造(:名称).company_name

factory :subject_children do 
    name Forgery(:name).company_name + ' child' 

    after :build do |subject| 
    subject_grand_parent = Subject.create(name: Forgery(:name).company_name) 
    subject_parent   = subject_grand_parent.children.create(name: Forgery(:name).company_name) 
    subject.parent   = subject_parent 
    subject.ancestry_depth = 2 
    end 
end 

Structure厂:

after(:build) do |structure| 
    structure.subjects << FactoryGirl.build(:subject) 
    structure.subjects << FactoryGirl.build(:subject_children) 
end