2013-07-06 46 views
0

我正在使用RSpec和FactoryGirl來測試我的Ruby-on-Rails-3應用程序。我正在使用工廠層次結構:如何從母廠獲得子工廠

FactoryGirl.define do 
    factory :local_airport do 

    ... attributes generic to a local airport 

    factory :heathrow do 
     name "London Heathrow" 
     iata "LHR" 
    end 

    factory :stansted do 
     name "Stansted" 
     iata "STN" 
    end 

    ... more local airports 
    end 
end 

在我的RSpec中,我有時希望能夠通過指定父工廠來創建所有子工廠。理想情況下,如:

describe Flight do 
    before(:each) do 
    # Create the standard airports 
    FactoryGirl.find(:local_airport).create_child_factories 
    end 
end 

非常感謝提前。

回答

0

調用它在測試中FactoryGirl代碼鑽研幾個小時後,好吧,我已經找到了解決辦法。有趣的是,FactoryGirl只在工廠存儲對父母的引用,而不是從父母到孩子。

在投機/工廠/ factory_helper.rb:

module FactoryGirl 
    def self.create_child_factories(parent_factory) 
    FactoryGirl.factories.each do |f| 
     parent = f.send(:parent) 
     if !parent.is_a?(FactoryGirl::NullFactory) && parent.name == parent_factory 
     child_factory = FactoryGirl.create(f.name) 
     end 
    end 
    end 
end 

在我的RSpec我現在可以這樣寫:

require 'spec_helper' 

describe Flight do 
    before(:each) do 
    # Create the standard airports 
    FactoryGirl.create_child_factories(:local_airport) 
    end 

    ... 

有一個問題是,我發現最好是有一個工廠層次結構很簡單(即兩級)。我從三層開始,發現我正在生成只存在於層次結構中的「抽象」工廠。我已經使用特徵將層次結構簡化爲兩個層次。

0

你不能真的告訴工廠建立所有的子工廠,因爲作爲一個子工廠就意味着它繼承了父類的屬性。但是你可以做的是添加一個特徵,例如:with_child_factories。然後,你的工廠將如下所示:

FactoryGirl.define do 
     factory :local_airport do 

     ... attributes generic to a local airport 

     factory :heathrow do 
      name "London Heathrow" 
      iata "LHR" 
     end 

     factory :stansted do 
      name "Stansted" 
      iata "STN" 
     end 

     ... more local airports 

     trait :with_child_factories do 
      after(:create) do 
      FactoryGirl.create(:heathrow) 
      FactoryGirl.create(:stansted) 
      ... 
      end 
     end 
     end 
    end 

然後,你可以用

 FactoryGirl.create(:local_airport, :with_child_factories) 
+0

謝謝你的建議。我唯一擔心的是,我需要保持與工廠正確相關的工廠清單。我希望能夠自動生成工廠列表。 –