在使用Webmock和CarrierWave远程上传的测试中不解析url

问题描述 投票:0回答:1

CarrierWave 有一个很好的功能,可以从远程位置上传图像https://github.com/rierwaveuploader/carrierwave#uploading-files-from-a-remote-location

我正在使用 Webmock 来存根远程请求,但它们不能很好地协同工作。我想这是因为 CarrierWave 下载图像的方式非常独特。

问题是 CarrierWave 解析主机,因此我无法对其进行存根。

ruby-on-rails rspec carrierwave webmock
1个回答
0
投票

我遇到了类似的问题,甚至VCR也没有解决。 (其实VCR给我透露了一些线索。)

我发现 Carrierwave 使用

Resolv.getaddresses
将给定 URL 的域名解析为 IP 地址(IPv4 和 IPv6),然后使用 IP 地址之一检索资源。所以,假设您模拟了 URL
https://wikipedia.org/path/to.png
;它可能会调用
https://103.102.166.224/path/to.png
https://[01:df2:e500:ed1a::1]/path/to.png
(随机,不知道为什么)。

我的解决方法是仅使用指定的 IP 地址和来自给定 IP 地址的存根请求来模拟

Resolv.getaddresses

# Mock Resolv.getaddresses
allow(Resolv).to receive(:getaddresses).with("example.com").and_return(["5.5.5.5"])

# Stub the URL but use the IP address instead
stub_request("https://5.5.5.5/path/to.png").to_return(status: 200, body: file)

# Now, you can call something like attachment.remote_file_url = "https://example.com/path/to.png"```
© www.soinside.com 2019 - 2024. All rights reserved.