2
如何可以存根據一個URL調用例如http://www.example.com/images/123.png並返回一個名爲123.png的圖像?Stub一個圖像的網址,並返回一個圖像
我正在使用Rails 3.2,Carrierwave。我試過Fakeweb,但有點難住。
如何可以存根據一個URL調用例如http://www.example.com/images/123.png並返回一個名爲123.png的圖像?Stub一個圖像的網址,並返回一個圖像
我正在使用Rails 3.2,Carrierwave。我試過Fakeweb,但有點難住。
研究了幾個小時後,原來很簡單:
FakeWeb.register_uri(:get, string_or_regxp_of_uri,
body: SupportFiles.uploaded_file("square.jpg"),
content_type: 'image/jpg')
我的問題是比較棘手:
我測試FB頭像,和我whitelst擴展
將上面的代碼不工作,因爲擴展名缺失
(FB頭像網址:https://graph.facebook.com/123/picture)
但真正的FB頭像將重定向到CDN或什麼是h作爲擴展
所以你需要添加另一個存根:
# Register a fake remote image
fake_avatar_uri = "https://graph.facebook.com/fake_avatar.jpg"
# Redirect to a fake uri
FakeWeb.register_uri(:get, %r|https://graph\.facebook\.com/|,
status: ["301", "Moved Permanently"],
location: fake_avatar_uri)
# Feed fake image for the fake uri
FakeWeb.register_uri(:get, fake_avatar_uri,
body: SupportFiles.uploaded_file("square.jpg"),
content_type: 'image/jpg')
的SupportFiles模塊(不我自己寫的:P):
require 'rack/test/uploaded_file'
module SupportFiles
extend ActiveSupport::Concern
included do
let(:an_image) do
open_file("square.jpg")
end
end
def open_file(filename)
File.open(support_file_path(filename))
end
# idea stolen from ActionDispatch::TestProcess#fixture_file_upload
def uploaded_file(filename)
Rack::Test::UploadedFile.new(support_file_path(filename))
end
module_function :uploaded_file
protected
def support_file_path(filename)
Rails.root.join("spec/support/files", filename)
end
module_function :support_file_path
end