我正在使用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
這很棒理論和所有......但是,如果測試代碼不適用於您正在使用的庫或系統,則毫無意義。 – noli 2011-05-24 16:55:25
是的,但這是集成測試的工作,而不是單元測試。在單元測試中,您需要驗證您的代碼是否發送了所有正確的呼叫。實際上,檢查S3最好是在手動測試中完成,或者像黃瓜功能一樣,您可以在其中測試整個堆棧而不僅僅是一個庫。 – Bira 2011-05-24 17:33:38