Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.

What is the proper way of stubbing this specific feature of Carrierwave in tests?

P.S. I have already disabled image processing in tests:

config.enable_processing = false if Rails.env.test?
like image 613
Alexander Popov Avatar asked Mar 30 '17 11:03

Alexander Popov


1 Answers

For me, the answer is to use the webmock gem. It blocks outbound HTTP connections during testing and allows you to easily stub responses.

After setting up the gem per the instructions, 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)

Worked like a charm with CarrierWave's remote_<uploader>_url feature.

like image 131
mroach Avatar answered Sep 30 '22 18:09

mroach