Ruby on rails 动态生成工厂属性

Ruby on rails 动态生成工厂属性,ruby-on-rails,ruby-on-rails-3,unit-testing,testing,factory-bot,Ruby On Rails,Ruby On Rails 3,Unit Testing,Testing,Factory Bot,我想做以下几点: classes = ["WelcomeMailing", "NoticeMailing", "FeedbackMailing"] #...... FactoryGirl.define do classes.each do |tclass| cl_attributes = ["body", "subject", "description", "title"] # this registers dynamically sequences, which i

我想做以下几点:

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
最后,我希望动态创建工厂(因为它们几乎都是相同的结构(继承的类))。但是正如您在代码中看到的,属性的设置不起作用

有什么建议吗?
谢谢

我自己解决了这个问题:

  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