2014-05-13 17 views
0

我有一個Member模型與兩個狀態機,stateaccount。我想使用factory_girl在我的測試中創建所有可能的狀態和帳戶組合的預定義列表。factory_girl中的預定義列表

例如,使用以下的組合:

combinations = [ 
    [:state_a, :account_a], [:state_a, :account_b], [:state_a, :account_c], 
    [:state_b, :account_a], [:state_b, :account_b], [:state_b, :account_c], 
    [:state_c, :account_a], [:state_c, :account_b], [:state_c, :account_c] 
] 

我想某種輔助的,例如create_list_for_all_states_and_accounts這將創建:

[ 
    Member(state: 'a', account: 'a'), 
    Member(state: 'a', account: 'b'), 
    Member(state: 'a', account: 'c'), 
    Member(state: 'b', account: 'a'), 
    # ... 
] 

這是可能的factory_girl

+0

這不正常。 factory_girl是關於創建單個實例。或者你是否想過預先創建所有這些實例並從工廠方法中一次一個地返回它們? –

+0

@DaveSchweisguth主要考慮爲所有組合創建實例,然後測試我的範圍,例如'expect(Member.some_scope).to ...' – tristanm

+0

您的意思是Member.some_scope返回您創建的實例之一?這聽起來像Rails夾具,而不是工廠。 (很多關於SO的討論) –

回答

0

如意見建議將在spec/support與輔助方法,一個文件來定義一個輔助方法,然後在你的規範使用它,無論你需要它最簡單的辦法:

def create_list_for_all_states_and_accounts(states = %w[ a b c ], accounts = %w[ a b c ]) 
    states.product(accounts).map do |state, account| 
    Member.create(state: state, account: account) 
    end 
end 

或者,如果你總是有相同的狀態和帳戶名,你可以這樣做:

def create_list_for_all_states_and_accounts(names = %w[ a b c ]) 
    names.repeated_permutation(2).map do |state, account| 
    Member.create(state: state, account: account) 
    end 
end 

如果你確實想用FactoryGirl創建使用特點的情況下,你可以定義這樣的工廠:

factory :member do 
    %w[ a b c ].product(%w[ a b c ]).each do |state, account| 
    trait :"state_#{state}_account_#{account}" do 
     state  state 
     account account 
    end 
    end 
end 

這將讓你像這樣創建實例:

FactoryGirl.create(:member, :state_a_account_b) 
0

我發現有些東西哈克,但嚴謹,高效的做到這一點。我想使用factory_girl來創建一組捆綁,這基本上是種子數據(但是由於我在測試中使用了database_cleaner,我不能僅僅使用seed.rb)。這裏是我做的事:

FactoryGirl.define do 
    factory :bundle do 
    factory :all_bundles do 
     price 1 
     name "bronze" 

     after :create do 
     FactoryGirl.create :silver_bundle 
     FactoryGirl.create :gold_bundle 
     FactoryGirl.create :platinum_bundle 
     end 
    end 

    factory :silver_bundle do 
     price 2 
     name "silver" 
    end 

    factory :gold_bundle do 
     price 3 
     name "gold" 
    end 

    factory :platinum_bundle do 
     price 4 
     name "platinum" 
    end 
    end 
end 

之後,我打電話create :all_bundles,和我做。

所以這裏的想法是:

  1. 定義所有的工廠
  2. 中的第一個,添加一個after :create塊(和/或after :stub一個,如果你需要一個)調用其他工廠

請注意,after :create塊應該位於子工廠(此處爲all_bundles),並且不在母廠(bundle)中,或者每個子工廠都會執行它:)