【问题标题】:how to stub active storage urls?如何存根活动存储 URL?
【发布时间】:2021-12-19 03:53:00
【问题描述】:

我正在为使用活动存储的应用编写系统测试。我正在测试的视图包括亚马逊 s3 上对象的预签名 URL。我显然想避免在我的测试中向 s3 发送 GET 请求。相反,我想“存根”活动存储,以便我的附件的 url 都指向我的测试机器上的一个特定文件(“/test_data/placeholder.jpg”),而不是指向 s3。

我的视图代码使用url_for 生成s3 url。如何存根url_for 以返回我想要的一个特定网址?

下面是我失败尝试的摘录。

在我看来(user.jbuilder.json):

json.user_thumbnail = url_for @user.photo.variant(resize: "100x100")

在我的测试中:

class UserPageTest < ApplicationSystemTestCase

  test "thumbnail appears on user page" do

    User.any_instance.stubs(:photo).returns(stub(:url => "/test_data/placeholder_thumbnail.jpg") ))

    visit '/user_profile/123'
  end
end

当我运行测试时,我得到了这个错误:

2021-11-04 20:26:40 -0400 Rack app ("GET /user/123.json" - (127.0.0.1)): #<Minitest::Assertion: unexpected invocation: #<Mock:0x7ff448c52af8>.to_model()

【问题讨论】:

  • 我们在我们的开发盒和测试服务器上使用 minio -- min.io -- 它的作用类似于 S3,只需要配置,所以代码是一样的。

标签: ruby-on-rails amazon-s3 rails-activestorage


【解决方案1】:

最后,我通过猴子修补我的测试中的 activestorage 来实现这一点。我根据我正在处理的对象的类重定向到不同的占位符文件。

ActiveStorage::Blobs::RedirectController.class_eval do 
  def show
    case @blob.attachments.first.record.class.name
    when "Video"
      redirect_to "/test_data/video.mp4"
    when "Photo"
      redirect_to "/test_data/photo.png"
    else
      raise StandardError.new "unhandled redirection in ActiveStorage::Blobs::RedirectController monkey patch"
    end
  end

#  include ActiveStorage::SetBlob

#  def show
#    expires_in ActiveStorage.service_urls_expire_in
#    redirect_to @blob.url(disposition: params[:disposition])
#  end

end


ActiveStorage::Representations::RedirectController.class_eval do 
  def show
    case @blob.attachments.first.record.class.name
    when "Video"
      redirect_to "/test_data/video.mp4"
    when "Photo"
      redirect_to "/test_data/photo.png"
    else
      raise StandardError.new "unhandled redirection in ActiveStorage::Blobs::RedirectController monkey patch"
    end
  end
end

【讨论】:

    猜你喜欢
    • 2019-05-21
    • 2018-09-20
    • 1970-01-01
    • 2018-10-29
    • 2021-01-04
    • 1970-01-01
    • 2022-10-02
    • 1970-01-01
    • 2021-04-22
    相关资源
    最近更新 更多