简体   繁体   中英

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.association :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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM