Do not resolve url in tests with Webmock and CarrierWave remote upload

141 Views Asked by At

CarrierWave has a nice feature for uploading images from remote locations https://github.com/carrierwaveuploader/carrierwave#uploading-files-from-a-remote-location

I'm using Webmock to stub remote requests, but they don't play nicely together. I guess it's because CarrierWave way of downloading images is quite unique.

The problem is that CarrierWave resolves host and I can't stub it because of that.

1

There are 1 best solutions below

0
Sovoboys On

I encountered a similar issue, and even VCR did not resolve it. (Actually, VCR revealed some clues about it to me.)

I discovered that Carrierwave uses Resolv.getaddresses to resolve the domain name of the given URL to IP addresses (both IPv4 and IPv6) and then retrieves the resource using one of the IP addresses. So, let's say you mock the URL https://wikipedia.org/path/to.png; it may call either https://103.102.166.224/path/to.png or https://[01:df2:e500:ed1a::1]/path/to.png (in random, not sure why).

My workaround for this is to mock Resolv.getaddresses with only a specified IP address and stub requests from the given IP address.

# 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"```