How to stub carrierwave in Rspec?

人盡茶涼 提交于 2020-01-11 00:07:28

问题


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:


TopicImageUploader.any_instance.stub(:download!)



回答2:


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:


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.




回答4:


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


来源:https://stackoverflow.com/questions/9562100/how-to-stub-carrierwave-in-rspec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!