ruby on rails - How do you pass an attribute value to the has_many through join table with FactoryGirl? -


food.rb factory:

factorygirl.define   factory :food     factory :apple       description 'apple'       sequence(:name) { |n| "apple #{n}"}       long_description 'apple'     end      factory :burger       description 'burger'       sequence(:name) { |n| "burger #{n}"}       long_description 'burger'     end      after(:create) |food|       [:fat, :protein, :carb, :fiber].each |nutrient|         food.nutrients << factorygirl.create(nutrient, :measurement)       end     end   end end 

nutrient.rb factory

factorygirl.define   factory :nutrient     factory :fat       name 'fat'       slug 'fat'     end      factory :protein       name 'protein'       slug 'protein'     end      factory :carb       name 'carbohydrates'       slug 'carbohydrates'     end      factory :fiber       name 'fiber'       slug 'fiber'     end      trait :measurement       measurement 'milligrams'     end   end end 

food_nutrient.rb factory

factorygirl.define   factory :food_nutrient     food     nutrient     qty rand(1..100)   end end 

feature test:

feature 'search'   scenario 'for apples'     user = factorygirl.create(:user)     apples  = 15.times.map { factorygirl.create(:apple) }     burgers = 5.times.map { factorygirl.create(:burger) }      ...more code   end end 

the error is: failure/error: apples = 15.times.map { factorygirl.create(:apple) } activerecord::recordinvalid: validation failed: qty can't blank

qty attribute in food_nutrient has_many :through join_table. how pass in variable?

you need add foodnutrient instances in after(:create) rather adding nutrients directly:

after(:create) |food|   [:fat, :protein, :carb, :fiber].each |nutrient|     food.food_nutrients << factorygirl.create(:food_nutrient,        nutrient: factorygirl.create(:nutrient, :measurement)     )   end end 

this use food_nutrient factory create foodnutrient instance associated each of 4 nutrients.


Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -