2013-07-28 30 views
1

我試圖通過定義1個工廠,而不是30FactoryGirl - 在一個循環

這是爲什麼不工作以節省時間定義幾個工廠?

(假設我們有一個叫做類方法: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: Attribute already defined: attribute

+0

我不認爲你需要調用'constantize'如果傳遞的實際上課。 –

回答

4

當你通過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| 
       send(attribute.to_sym, Faker::Name.first_name) ##### Use send 
      end 
     end   
    end 
end 
+0

我建議你強調一下,你打電話給'send' –

+0

謝謝。簡而言之重點:)我後來閱讀了它,並指出他們正在使用缺少的方法實現FactoryGirl DSL。一旦我們發送(請求)一個名爲attribute.to_sym的方法,就會激活方法丟失,然後他們創建一個名爲attribute.to_sym的方法,返回Faker :: Name.first_name .. – AndPy