2011-03-08 49 views
1

我一直遇到同樣的問題,如果我是唯一遇到此問題的人,並且期望有人有更好的方法來做到這一點,我會感到驚訝。當我創建一個具有相關工廠(關聯)的工廠時,父級模型不會使用已添加的模型進行更新。可能更容易在代碼中解釋。factory_girl - has_many關係和刷新父模型

說我有:

Factory.define :company do |a| 
    a.name 'Acme' 
end 
Factory.define :office do |a| 
    a.name 'London' 
    a.association :company, :factory => :company 
end 

,我執行此代碼:

london = Factory.create(:office) 
sanfran = Factory.create(:office, :name => 'San Fran' , :company = london.company) 

那麼如果我運行這個測試

london.company.offices.count.should eql(2) 

失敗,因爲公司的Acme是以前實例倫敦甚至是聖弗蘭創建,並且因爲company.offices.new不用於創建新模型, mpany模型從未更新。

我已經能夠解決此問題的唯一方法是寫我的測試如下:

london.company(true).offices.count.should eql(2) 

其強制進行刷新。

但是,這在我的測試中每次都做得不是很理想,特別是當它正在測試的代碼不應該依賴於此時。

+0

請您提供更多的上下文嗎?這些工廠看起來應該是他們應該工作的 - 我正在成功地使用這些工廠 - 所以也許線索在測試中。張貼這些,我會看看。 – 2011-06-01 08:31:22

+0

':company = london.company'是嗎?它不應該是':company => london.company' – 2011-06-03 16:37:38

回答

0

有沒有理由不能先創建母公司?在創建子對象後,從預先實例化的父項中獲取計數似乎沒有問題。

describe Company do 
    describe "office associations" do 
    before(:each) do 
     @company = Factory(:company) 
    end 

    it "should have the correct number of offices" do 
     o1 = Factory(:office, :company => @company) 
     o2 = Factory(:office, :company => @company) 
     @company.offices.should =~ [o1, o2].flatten # <= Not sure why, but each call to Factory appears to return an array 
    end 
    end