2

如何存根对 url 的调用,例如http://www.example.com/images/123.png并返回一个名为 123.png 的图像?

我正在使用 Rails 3.2,Carrierwave。我试过 Fakeweb,但有点难过。

4

1 回答 1

3

经过几个小时的研究,结果很简单:

FakeWeb.register_uri(:get, string_or_regxp_of_uri,
        body: SupportFiles.uploaded_file("square.jpg"),
        content_type: 'image/jpg')

我的问题更棘手:
我正在测试 FB 头像,我得到了 whitelst 扩展

由于缺少扩展,上述代码将不起作用
(FB 头像 URL: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
于 2012-09-22T03:27:11.310 回答