我想做以下事情:
classes = ["WelcomeMailing", "NoticeMailing", "FeedbackMailing"] #......
FactoryGirl.define do
classes.each do |tclass|
cl_attributes = ["body", "subject", "description", "title"]
# this registers dynamically sequences, which i can use later (this works already!)
define_sequences(cl_attributes.map{|a| tclass.underscore + "_" + a})
factory tclass.underscore.to_sym do
cl_attributes.each do |aattr|
# here i want to generate the attributes of the factory class dynamically..
aattr { generate (tclass.underscore + "_" + aattr).to_sym }
# but it doesnt work
# => pry(main)> FactoryGirl.create(:custom_mailing_draft)
# FactoryGirl::AttributeDefinitionError: Attribute already defined: aattr
# or
eval(aattr) { generate (tclass.underscore + "_" + aattr).to_sym } # also not with
# =>factory_girl/definition_proxy.rb:36:in `add_attribute': Both value and block given (FactoryGirl::AttributeDefinitionError)
end
end
end
end
最后我想动态创建工厂(因为它们几乎都是相同的结构(继承类))。但就像你在代码中看到的那样,属性的设置不起作用。
有什么建议吗? 谢谢!
答案 0 :(得分:0)
我自己解决了:
classes.each do |tclass|
FactoryGirl.define do
define_sequences(attributes.map{|a| tclass.underscore + "_" + a})
clstr = "factory :#{tclass.underscore} do;"
attributes.each do |aattr|
clstr += "#{aattr} { generate :#{(tclass.underscore + "_" + aattr).to_sym} };"
end
clstr += "end"
eval(clstr)
end
end