2011-05-24 31 views
0

我正在使用CarrierWave將圖像上傳到Imagecollection模型,並且想要測試當我上載圖像時,它實際上可以在線獲取。而當我刪除圖像時,它實際上被刪除。如何在Rspec中測試來自模型規範的HTTP請求

我正在使用S3後端,所以我想在模型本身進行測試,而不必具有任何控制器依賴性,或者運行集成測試。所以我需要構建url,發出HTTP reequest,並測試它的返回碼。此代碼不能正常工作,但有一種方法可以做到類似如下的內容:

describe "once uploaded" do 
    subject {Factory :company_with_images} 

    it "should be accessible from a URL" do 
    image_url = subject.images.first.image.url 
    get image_url         # Doesn't work 
    response.should be_success      # Doesn't work 
    end 
end 

編輯:

我最終加入這個對我的Gemfile

gem rest-client 

並使用:fog後端進行我的測試。理想情況下,我可以在測試期間改變後端,類似

before do 
    CarrierWave.configure do |config| 
    config.storage = :fog 
    end 
end 

describe tests 
end 

after do 
    CarrierWave.configure do |config| 
    config.storage = :end 
    end 
end 

但是,這似乎並沒有實際做任何事情。

describe "once uploaded" do 
    describe "using the :fog backend" do 
    subject {Factory :company_with_images} 

    # This test only passes beecause the S3 host is specified in the url. 
    # When using CarrierWave :file storage, the host isn't specified and it 
    # fails 
    it "should be accessible from a URL" do 
     image_url = subject.images.first.image.url 
     response = RestClient.get image_url 
     response.code.should eq(200) 
    end 
    end 

    describe "using the :file backend" do 
    subject {Factory :company_with_images} 

    # This test fails because the host isn't specified in the url 
    it "should be accessible from a URL" do 
     image_url = subject.images.first.image.url 
     response = RestClient.get image_url 
     response.code.should eq(200) 
    end 
    end 
end 

回答

0

我最終重新定義規格如下

describe "using the :fog backend" do 
    subject {Factory :company_with_images} 

    it "should be accessible from a URL" do 
     image_url = subject.images.first.image.url 
     rest_response(image_url).code.should eq(200) 
    end 
    end 

這個幫手

def rest_response url 
    # https://github.com/archiloque/rest-client 
    RestClient.get(url){|response, request, result| response } 
end 

和使用RESTClient實現寶石

1

我對CarrierWave不熟悉,您應該測試您的代碼,而不是任何外部庫或它所依賴的服務。換句話說,你想測試你的班級,而不是S3。我建議嘲笑你的模型對S3進行的調用,以驗證它使所有正確的調用。

+0

這很棒理論和所有......但是,如果測試代碼不適用於您正在使用的庫或系統,則毫無意義。 – noli 2011-05-24 16:55:25

+1

是的,但這是集成測試的工作,而不是單元測試。在單元測試中,您需要驗證您的代碼是否發送了所有正確的呼叫。實際上,檢查S3最好是在手動測試中完成,或者像黃瓜功能一樣,您可以在其中測試整個堆棧而不僅僅是一個庫。 – Bira 2011-05-24 17:33:38

0

除非文件實際上傳到s3,否則不能測試s3。在carrierwave中,默認情況下,它不會上傳到s3。

代替,測試IMAGE_URL是正確的:

image_url = subject.images.first.image.url 
image_url.should == "http://.....' 
+0

謝謝,但是,這是整個想法。把它看作是模型層的全面集成測試 – noli 2011-05-24 17:35:24

+0

你沒有得到你想要的答案,因爲你正在嘗試去做那些人們沒有做的事情。您需要快速,獨立和可重複的測試 - 在您的測試中測試S3和Google的服務會打破這種情況,這就是爲什麼它不受歡迎。 – 2011-05-24 20:22:22

+0

好的公平點..我想我的誤解是,爲什麼人們不這樣做。我完全理解快速測試的需要,但在一天結束時,我需要一個工作應用程序,而不是通過測試。所以當我運行我的測試套件時,如果因爲S3或Google的服務而失敗,我需要了解它 - 不要被誤認爲認爲一切都很好,因爲測試是綠色的 – noli 2011-06-10 13:04:57

相關問題