2012-05-31 28 views
1

在我的模型中,我必須選擇一個資產,保存在editorial_asset表中。文件上傳,factory_girl&database_cleaner

include ActionDispatch::TestProcess 

FactoryGirl.define do 
    factory :editorial_asset do 
    editorial_asset { fixture_file_upload("#{Rails.root}/spec/fixtures/files/fakeUp.png", "image/png") } 
    end 
end 

,所以我在我的模型廠已附着在:editorial_asset

上傳一個協會工作的偉大,但花太多時間(每例如1秒)

我不知道它是否可以創建每個例子之前上傳一次,並在工廠說:「找到而不是創建」

但是,與database_cleaner的問題,我不能除了表:transaction,截斷需要25秒,而不是40毫秒!

編輯

工廠需要的資產

FactoryGirl.define do 
    factory :actu do 
    sequence(:title) {|n| "Actu #{n}"} 
    sequence(:subtitle) {|n| "Sous-sitre #{n}"} 

    body Lipsum.paragraphs[3] 

    # Associations 
    user 
    # editorial_asset 
    end 
end 

型號規格

require 'spec_helper' 

describe Actu do 
    before(:all) do 
    @asset = create(:editorial_asset) 
    end 

    after(:all) do 
    EditorialAsset.destroy_all 
    end 

    it "has a valid factory" do 
    create(:actu).should be_valid 
    end 

end 

所以工作方式是

it "has a valid factory" do 
    create(:actu, editorial_asset: @asset).should be_valid 
    end 

,但沒有辦法注入自動關聯?

回答

1

由於您使用的是RSpec,因此您可以使用before(:all)塊來設置這些記錄一次。但是,在所有塊中完成的任何事情都是而不是被視爲交易的一部分,因此您必須自己在後續所有塊中刪除DB中的任何內容。

您的工廠對於與編輯資產有關聯的模型,可以,是的,在創建它之前嘗試先找到一個模型。而不是做類似association :editorial_asset的你可以這樣做:那麼

editorial_asset { EditorialAsset.first || Factory.create(:editorial_asset) } 

你RSpec的測試可能是這樣的:

before(:all) do 
    @editorial = Factory.create :editorial_asset 
end 

after(:all) do 
    EditorialAsset.destroy_all 
end 

it "already has an editorial asset." do 
    model = Factory.create :model_with_editorial_asset 
    model.editorial_asset.should == @editorial 
end 

瞭解更多關於前和Rspec的GitHub的wiki頁面上或津津樂道塊之後文檔:

https://github.com/rspec/rspec-rails

https://www.relishapp.com/rspec

+0

我編輯我的問題與我的規格,我認爲這是好的,但與database_cleaner,我不能說找到或創建,一切都被破壞 – m4tm4t

+0

使用DatabaseCleaner.strategy =:截斷,{除:[「editorial_assets」]}'工作與查找或創建偉大。但現在清潔非常緩慢。我正在用postgresql運行Archlinux,似乎它與linux相關 – m4tm4t

+0

它與EXT4相關。經過一些調整後,速度會更快,但具有15個示例的用戶規範需要2秒的截斷時間,而不是40ms的事務時間。我想我會嘗試使用reiserfs – m4tm4t