【问题标题】:Stub a image url and return an image存根图像 url 并返回图像
【发布时间】:2012-07-27 13:30:48
【问题描述】:

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

我使用的是 Rails 3.2,Carrierwave。我试过 Fakeweb,但有点难过。

【问题讨论】:

    标签: ruby-on-rails carrierwave fakeweb


    【解决方案1】:

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

    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 或具有扩展名的东西
    所以你需要添加另一个存根:

    # 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-21
      • 1970-01-01
      • 1970-01-01
      • 2021-09-01
      • 2018-08-10
      • 2017-07-20
      • 2020-02-19
      • 1970-01-01
      相关资源
      最近更新 更多