ruby-on-rails – 在FactoryGirl中创建一个值数组,每个值都是唯
发布时间:2020-12-17 03:47:11 所属栏目:百科 来源:网络整理
导读:我有这个工厂定义: factory :post,:parent = :post_without_countries,class: Post do |p| p.country_ids {|country_ids| [country_ids.association(:country),country_ids.association(:country)]} end 而且我希望它输出两个独特的国家.相反,它只是插入与
我有这个工厂定义:
factory :post,:parent => :post_without_countries,class: Post do |p| p.country_ids {|country_ids| [country_ids.association(:country),country_ids.association(:country)]} end 而且我希望它输出两个独特的国家.相反,它只是插入与协会相同的国家/地区两次: #<Post id: nil,title: "Atque id dolorum consequatur.",body: "Praesentium saepe ullam magnam. Voluptatum tempora ...",created_at: nil,updated_at: nil,user_id: 1> [#<Country id: 1,name: "Dominican Republic",isocode: "lyb",created_at: "2012-10-20 13:52:18",updated_at: "2012-10-20 13:52:18">,#<Country id: 1,updated_at: "2012-10-20 13:52:18">] 有任何想法吗? 解决方法
而不是做:
2.times { post.countries << FactoryGirl.create(:country) } 在RSpec中,你可以像这样制作一个after_create钩子: after_create do |post| 2.times { post.countries << FactoryGirl.create(:country) } end 如果您需要自定义要创建国家/地区的次数,可以创建一个瞬态属性: #in the post factory definition ignore do num_countries 0 #default to zero end #different after_create after_create do |post,proxy| proxy.num_countries.times { post.countries << FactoryGirl.create(:country) } end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |