如何在 Carrierwave 中存根从远程 url 下载

How to stub download from remote url in Carrierwave

我有一个 User AR 模型,当我保存一个填充值为 remote_avatar_urlUser 实例时,Carrierwave 会自动下载头像。有关此功能的更多信息 here

现在,在我的测试中,我想阻止这种行为。我知道我能做到:

allow_any_instance_of(UserAvatarUploader).to receive(:download!)

但是,rspec-mocks 文档 discourages the use of allow/expect_any_instance_of

在测试中对 Carrierwave 的这一特定功能进行存根的正确方法是什么?

P.S。我已经在测试中禁用了图像处理:

config.enable_processing = false if Rails.env.test?

对我来说,答案是使用webmock gem。它在测试期间阻止出站 HTTP 连接,并允许您轻松存根响应。

按照说明设置 gem 后,我将其添加到我的测试中:

body_file = File.open(File.expand_path('./spec/fixtures/attachments/sample.jpg'))
stub_request(:get, 'www.thedomainofmyimage.example.net').
  to_return(body: body_file, status: 200)

与 CarrierWave 的 remote_<uploader>_url 功能完美结合。