Записать URL-адрес изображения и вернуть изображение
Как я могу заблокировать вызов URL, например, http://www.example.com/images/123.png и вернуть изображение с именем 123.png?
Я использую Rails 3.2, Carrierwave. Я пробовал Fakeweb, но немного озадачен.
2 ответа
Решение
После нескольких часов исследований выясняется, что все просто:
FakeWeb.register_uri(:get, string_or_regxp_of_uri,
body: SupportFiles.uploaded_file("square.jpg"),
content_type: 'image/jpg')
Моя проблема сложнее:
Я тестирую аватар FB, и у меня есть последнее расширение
Приведенный выше код НЕ будет работать, так как расширение отсутствует
(URL аватара FB: https://graph.facebook.com/123/picture)
Но настоящий аватар FB будет перенаправлять на CDN или что-то, имеющее расширение
Так что вам нужно добавить еще одну заглушку:
# 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
Чтобы имитировать внешний URL-адрес изображения с файлом, вы можете заглушить запрос с любымIO
объект, например:
describe '#create' do
it 'creates item' do
io_object = fixture_file_upload('images/1.png', 'image/png').tempfile.to_io
stub_request(:get, 'http://www.example.com/images/123.png')
.to_return(status: 200, body: io_object, headers: {})
params = {
name: 'Good Item',
remote_file_url: 'http://www.example.com/images/123.png')
}
api_post(items_path, params)
end
end