18

我正在從attachment_fu升級到carrierwave,因爲attachment_fu在導軌3中斷了。Rails 3載波測試夾具?

沒有一個測試能夠運行,因爲我們有無效的fixtures,它使用attachment_fu的附件文件的語法。

例如,我們有一個Post模型,它有一個PostAttachment。這裏是長什麼樣的附着後夾具的數據,如:

a_image: 
    post_id: 1 
    attachment_file: <%= Rails.root>/test/files/test.png 

這是我得到的錯誤:

ActiveRecord::StatementInvalid: PGError: ERROR: column "attachment_file" of relation "post_attachments" does not exist 
LINE 1: INSERT INTO "post_attachments" ("post_id", "attachment_file"... 

attachment_file會被attachment_fu接走了,它會照顧所有處理爲模型創建attachment_fu附件。

有沒有辦法在燈具中有圖像附件,但使用CarrierWave呢?

回答

8

嘗試傳遞文件而不是字符串。

a_image: 
    post_id: 1 
    attachment_file: File.open(Rails.root.join("test/files/test.png")) 

這工作我使用FactoryGirl

注意事項:編輯感謝@dkobozev

+3

'File.open(Rails.root + 「/test/files/test.png」)'不適用於工作我。 'File.open(Rails.root.join(「test/files/test.png」))''。 – dkobozev

+0

我改變了它。非常感謝。 – e3matheus

+1

在當前版本的carrierwave上,這不適合我。我試過引用/轉義/ ERBing上面的'File.open ...'調用。我也嘗試過使用'Rack :: Test :: UploadedFile.new(Rails.root.join(「test/files/test.png」))',它在作爲參數傳遞時起作用。 – Leo

19

我已經成功地得到這個工作的唯一方法是專門使用存儲提供商測試不會實際保存/讀取文件。

在您的config/initializers/carrier_wave.rb中添加一個實現存儲提供程序最小接口的NullStorage類。

# NullStorage provider for CarrierWave for use in tests. Doesn't actually 
# upload or store files but allows test to pass as if files were stored and 
# the use of fixtures. 
class NullStorage 
    attr_reader :uploader 

    def initialize(uploader) 
    @uploader = uploader 
    end 

    def identifier 
    uploader.filename 
    end 

    def store!(_file) 
    true 
    end 

    def retrieve!(_identifier) 
    true 
    end 
end 

然後,當初始化CarrierWave添加子句測試環境,例如,

if Rails.env.test? 
    config.storage NullStorage 
end 

下面是參考一個gist of my complete carrier_wave.rb。它還包括如何在登臺/製作中爲上傳設置S3以及如何在本地存儲中進行開發,以便您瞭解如何在上下文中配置CarrierWave。

一旦配置了CarrierWave,您可以簡單地將任何字符串放在燈具列中以模擬上傳的文件。

+0

當我在工廠嘗試使用文件arg時,出現'ArgumentError: 不是公認的存儲提供程序錯誤。按照您的建議,轉換爲字符串可以使其工作!好極了!謝謝! – brookr

+2

嗯,我很有希望,但是...當我訪問我的功能規格中的表單字段頁面時,仍然顯示爲「不是公認的存儲提供商」。有沒有辦法將NullStorage註冊爲公認的提供者? – brookr

+0

我不完全確定NullStorage的功能;但我有單元測試,可以通過電子郵件發送以前上傳文件的附件 - 如何測試這些附件?我嘗試了上述步驟,他們似乎沒有幫助。謝謝。 – Gerry

1

爲了能夠使用已經上傳文件以及在測試中上傳的燈具,我最近在CarrierWave上玩了一下。我寫了一個article關於我該怎麼做。

+0

文件不會永久保存,但測試也不會傳遞給我。 – Zhang

-4

我們剛剛一起移除了燈具,系統會爲每個測試播種此文件。問問自己......你需要在這裏測試這些固定裝置嗎?沒有可能不是。和固定裝置不要砰!所以我們只是使用Model.create!(...)與測試的具體數據

2

config/initializers/carrier_wave。RB

在Rails 4

# class NullStorage is defined here before the following block 

if Rails.env.test? 
    CarrierWave.configure do |config| 
    config.storage NullStorage 
    end 
end 

&在夾具:

a_image: 
    post_id: 1 
    attachment_file: <%= File.open(Rails.root.join("test/files/test.png")) %>