13

I want to stub carrierwave to prevent it from fetch images on the web during my tests. How would I stub things to achieve this?

My crawler parses a remote web page, and saves one image url into the model. Carrierwave will fetch that image automatically during the save operation. It works well.

However I have a test about the parsing of pages, and every-time it will download the file, which slows down the testing.

UPDATE:

I mount the uploader as the following (in the pre-existing paperclip column)

mount_uploader :image, TopicImageUploader, :mount_on => :image_file_name

I tried to stub the following, but neither worked:

Topic.any_instance.stub(:store_image!)
Topic.any_instance.stub(:store_image_file_name!)
Topic.any_instance.stub(:store_image_remote_url!)
1
  • try this: allow(Topic).to receive(:store_image!)
    – ajahongir
    Nov 2, 2014 at 8:17

4 Answers 4

15
+50
TopicImageUploader.any_instance.stub(:download!)
1
  • 4
    New RSpec syntax: allow_any_instance_of(TopicImageUploader).to receive(:download!)
    – mikdiet
    Jun 18, 2015 at 13:29
11

This is what I'm using in my spec_helper:

class CarrierWave::Mount::Mounter
  def store!
  end
end

This completely blocks all real file uploads (note that I'm using this with carrier wave 0.5.8, which is newest version at the time of writing, if you're using much older version, it might differ). If you want to control tests which stub uploads, you could use:

CarrierWave::Mount::Mounter.any_instance.stub(:store!)
3
  • your solution is more generalized which I like. However I am using 0.5.8 and the stubbing on any_instance seems to have no effects.
    – lulalala
    Mar 12, 2012 at 2:25
  • Works great for for me in carrierwave 0.7.1. With Mocha you can use: CarrierWave::Mount::Mounter.any_instance.stubs(:store!) in spec_helper and in the test: CarrierWave::Mount::Mounter.any_instance.unstub(:store!)
    – AJP
    Nov 23, 2012 at 14:27
  • For Uploader and newer version of rspec-mocks it's allow_any_instance_of(CarrierWave::Uploader::Base).to receive(:store!)
    – dominik
    Apr 28, 2021 at 14:55
7

I reduced my test-suite time from 25 seconds to just 2 seconds with a simple config in the CarrierWave initializer:

# config/initializers/carrier_wave.rb
CarrierWave.configure do |config|
  config.enable_processing = false if Rails.env.test?
end

This config skips the image manipulation (resizing, cropping, ...) of ImageMagick, MiniMagick ect.

1
allow_any_instance_of(CarrierWave::Uploader::Base).to receive(:store!).and_return nil

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.