1

我试图通过定义 1 个工厂而不是 30 个来节省一些时间。

为什么这不起作用?

(假设我们有一个名为 :wanted_attributes 的类方法)

require 'rubygems' 
require 'faker'

models = %w[Model1 Model2]

models.each do |model|
    factoryname = model.downcase + "_e"

    FactoryGirl.define do 
        factory factoryname.to_sym, :class => model do 
            model.constantize.wanted_attributes.each do |attribute|
                attribute Faker::Name.first_name
            end
        end         
    end
end

我收到错误:

FactoryGirl::AttributeDefinitionError:属性已定义:属性

4

1 回答 1

4

当您循环遍历wanted_attributes 时,您总是在创建一个名为“attribute”的属性。您需要使用 send 方法来确保使用属性变量的值而不是名称“attribute”:

require 'rubygems' 
require 'faker'

models = %w[Model1 Model2]

models.each do |model|
    factoryname = model.downcase + "_e"

    FactoryGirl.define do 
        factory factoryname.to_sym, :class => model do 
            model.constantize.wanted_attributes.each do |attribute|
                send(attribute.to_sym, Faker::Name.first_name) ##### Use send
            end
        end         
    end
end
于 2013-07-28T16:17:00.033 回答