How to stub download from remote url in Carrierwave
I have an User
AR model and when I save an instance User
with a populated value remote_avatar_url
, Carrierwave automatically loads the avatar. Read more about this feature here .
Now, in my tests, I want to muffle this behavior. I know I can:
allow_any_instance_of(UserAvatarUploader).to receive(:download!)
however, the documentation rspec-mocks
discourages useallow/expect_any_instance_of
.
What is the proper way to zero out this particular Carrierwave function in tests?
PS I have already disabled image processing in tests:
config.enable_processing = false if Rails.env.test?
source to share
For me, the answer is to use the webmock gem. It blocks outgoing HTTP connections during testing and makes it easy to block responses.
After setting up the gem as instructed, I added this to my tests:
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)
Works like a charm with CarrierWave feature remote_<uploader>_url
.
source to share