[英]How to stub download from remote url in Carrierwave
I have a User
AR model and when I save a User
instance with a populated value of remote_avatar_url
, Carrierwave automatically downloads the avatar. 我有一个
User
AR模型,当我用一个填充值为remote_avatar_url
的User
实例保存时,Carrierwave会自动下载头像。 More info about this feature here . 这里有关于此功能的更多信息。
Now, in my tests, I want to stub this behavior. 现在,在我的测试中,我想要存根这种行为。 I know I can do:
我知道我能做到:
allow_any_instance_of(UserAvatarUploader).to receive(:download!)
however, the rspec-mocks
documentation discourages the use of allow/expect_any_instance_of
. 但是,
rspec-mocks
文档不鼓励使用allow/expect_any_instance_of
。
What is the proper way of stubbing this specific feature of Carrierwave in tests? 在测试中将Carrierwave的这一特定功能存在的正确方法是什么?
PS I have already disabled image processing in tests: PS我已经在测试中禁用了图像处理:
config.enable_processing = false if Rails.env.test?
For me, the answer is to use the webmock gem. 对我来说,答案是使用webmock gem。 It blocks outbound HTTP connections during testing and allows you to easily stub responses.
它在测试期间阻止出站HTTP连接,并允许您轻松存根响应。
After setting up the gem per the instructions, I added this to my tests: 根据说明设置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)
Worked like a charm with CarrierWave's remote_<uploader>_url
feature. 像CarrierWave的
remote_<uploader>_url
功能一样工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.