开发者

Factory girl association

I've written a rspec test which adds into my rubric some units.

I have two models => Rubric and Units. Rubrics have many units. It looks like this:

@rubric.units.push Factory :text_unit
@rubric.save

Then I found factory_girl and tried to rewrite this code as a factory. But it is not working.

How can i write this association in Factory Girl. I tried this:

  factory :common_rubric , :class => :common_info_rubric do |f|
    f.sequence(:name) {|n| "common_info_rubric#{n}"}
  end

  factory :text_unit, :class => text_info_unit do |f|
    f.ass开发者_运维技巧ociation :common_rubric_with_unit
    f.sequence(:name) {|n| "text_unit#n}" }
  end

  factory :common_rubric_with_unit , :parent => :common_rubric do |f|
    f.units { |unit| unit.association(:text_info_unit) }
  end   

I always have error

SystemStackError:
       stack level too deep


You have a circular reference there. When you create a text_unit it creates an associated common_rubric_with_unit. The definition for common_rubric_with_unit creates an associated text_unit and we're back at the start.

You'll need to remove one of the associations from either side, this should work:

factory :text_unit, :class => text_info_unit do |f|
  f.association :common_rubric_with_unit
  f.sequence(:name) {|n| "text_unit#n}" }
end

factory :common_rubric_with_unit , :parent => :common_rubric do |f|
end


All problem was the undefault name of table in models. And after read http://robots.thoughtbot.com/post/254496652/aint-no-calla-back-girl i solve the problem

 factory :common_rubric , :class => :common_info_rubric do |f|
    f.sequence(:name) {|n| "common_info_rubric#{n}"}
  end

  factory :text_unit, :class => :text_info_unit do |f|
    f.sequence(:name) {|n| "text_unit#{n}" }
  end

  factory :common_rubric_with_unit, :parent => :common_rubric do |f|
    f.after_create {|a| Factory(:text_unit, :rubric => a) }
  end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜