2014-12-05 48 views
0

這裏是我的代碼片段:FactoryGirl集合不會結轉

context "(3) Integration" do 

    let(:ad) { create(:ad) } 
    let(:property) { create(:property, owner_id: 1) } 
    let(:visitor_session) { create(:visitor_session, property_id: property.id) } 
    let(:impression) { create(:impression, ad_id: ad.id, visitor_session_id: visitor_session.id) } 

    # before(:each) do 
    # DatabaseCleaner.clean_with(:truncation) 
    # end 

    describe "(a) An ad can check it's impressions" do 
     it do 
     expect(ad.impressions).to include impression 
     end 
    end 

    describe "(b) An ad can check the total impression count" do 
     it do 
     expect(ad.impressions.count).to eq 1; 
    end 
    end 
end 

第二次測試失敗,當它真的應該傳球,而我很大吃一驚。如果我在第一次測試的中間通行binding.pry,輸出爲ad.impressions返回CollectionProxy:

#<ActiveRecord::Associations::CollectionProxy [#<Impression id: 1, start_at: "2014-12-05 17:17:40", duration: 10, is_valid: true, ad_id: 1, visitor_session_id: 1, created_at: "2014-12-05 17:17:49", updated_at: "2014-12-05 17:17:49">]> 

調用此數,在撬控制檯,返回1

當值我得到第二個測試,ad似乎是在第一次測試相同的對象,除了現在它的印象CollectionProxy是一個空的數組。

我懷疑這可能是一個數據庫清理問題,這就是爲什麼我評論它,但它似乎沒有任何影響。這裏是我的spec_helper對於那些需要更多的細節:

require 'factory_girl' 
require 'database_cleaner' 
require 'devise' 

RSpec.configure do |config| 

    config.include Devise::TestHelpers, type: :controller 
    config.include FactoryGirl::Syntax::Methods 

    config.before(:suite) do 
    DatabaseCleaner.clean_with(:truncation) 
    end 

    config.before(:each) do 
    DatabaseCleaner.strategy = :transaction 
    end 

    config.before(:each, :js => true) do 
    DatabaseCleaner.strategy = :truncation 
    end 

    config.before(:each) do 
    DatabaseCleaner.start 
    end 

    config.after(:each) do 
    DatabaseCleaner.clean 
    end 
    config.color = true; 

end 

爲什麼我收集的不是堅持到第二個測試?

回答

2

第一次測試通過的唯一原因是您直接在其中調用impression,這會導致評估let(:impression)塊 - 這會在第一次調用時創建展示記錄。

由於第二次測試根本不會調用impression,該記錄永遠不會被創建。

要修復它使用let!將測試代碼本身之前評估塊:

let!(:impression) { create(:impression, ad_id: ad.id, visitor_session_id: visitor_session.id) } 

let and let!文檔獲取更多信息。