10

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?
Alexander Popov
  • 23,073
  • 19
  • 91
  • 130

1 Answers1

7

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.

mroach
  • 2,403
  • 1
  • 22
  • 29