ruby on rails - Factorygirl create complex collection -


i have item , category. want have multiple items, each multiple categories. don't want each item have different categories, rather associate common set of categories.

is there way achieve using factorygirl dsl?

here how did using helper module:

module features   module itemshelpers     def create_items_with_categories       parents = create_list :category, 2       children = []       5.times         children << (create :category, parent: parents.sample)       end       10.times         item = build :item         item.categories << children.sample(3)         item.save       end     end   end end 

by looking @ code, assume, item has many categories:

sequence :name |n|   "item - #{n}" end  factory :item   name { generate(:name) }   # other fields here..   ignore # in latest version, is: "transient do.."     categories_count 5   end    after(:create) |item, evaluator|     categories { factorygirl.create_list(:category, evaluator.categories_count) }   end end 

you can use as:

  let(:categories) { create_list(:category, 10) }   let(:items) { create_list(:item, 5, categories: categories) } 

update: in many cases, when specs grow, won't have bothered adding extra: categories while creating items it'll created default values, unless specified. hence, ignore/ transient keeping classy.

so can do:

let(:items) { create_list(:items, 10, categories_count: 3) } # when need 3 categories per item!! 

at end, comes down preference , coding structure follow. prefer have both don't have bother adding categories list when cretaing item or items factory.


Comments

Popular posts from this blog

java - How to specify maven bin in eclipse maven plugin? -

single sign on - Logging into Plone site with credentials passed through HTTP -

php - Why does AJAX not process login form? -