How to stub carrierwave in Rspec?

2020-03-01 07:54发布

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!)

4条回答
我只想做你的唯一
2楼-- · 2020-03-01 08:27

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楼-- · 2020-03-01 08:30
allow_any_instance_of(CarrierWave::Uploader::Base).to receive(:store!).and_return nil
查看更多
Summer. ? 凉城
4楼-- · 2020-03-01 08:40

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.

查看更多
兄弟一词,经得起流年.
5楼-- · 2020-03-01 08:45
TopicImageUploader.any_instance.stub(:download!)
查看更多
登录 后发表回答