Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stub carrierwave in Rspec?

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!)
like image 245
lulalala Avatar asked Mar 05 '12 05:03

lulalala


3 Answers

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.

like image 165
Philip Giuliani Avatar answered Oct 19 '22 07:10

Philip Giuliani


TopicImageUploader.any_instance.stub(:download!)
like image 15
chrisun Avatar answered Nov 14 '22 03:11

chrisun


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!)
like image 11
Andrius Chamentauskas Avatar answered Nov 14 '22 04:11

Andrius Chamentauskas