如何在Rspec中存根载波?
我想在我的测试中使用stubwave来阻止它在网上获取图像。 我将如何实现这一目标?
我的抓取工具解析远程网页,并将一个图像url保存到模型中。 Carrierwave将在保存操作期间自动获取该图像。 它运作良好。
但是我有一个关于页面解析的测试,并且每次都会下载文件,这会减慢测试速度。
更新:
我按以下方式安装上传器(在预先存在的回形针列中)
mount_uploader :image, TopicImageUploader, :mount_on => :image_file_name
我试图将以下内容存根,但都没有奏效:
Topic.any_instance.stub(:store_image!) Topic.any_instance.stub(:store_image_file_name!) Topic.any_instance.stub(:store_image_remote_url!)
TopicImageUploader.any_instance.stub(:download!)
这是我在spec_helper中使用的内容:
class CarrierWave::Mount::Mounter def store! end end
这完全阻止了所有真正的文件上传(注意我使用的是载波0.5.8,这是写作时的最新版本,如果你使用的是更旧的版本,它可能会有所不同)。 如果要控制哪些存根上传的测试,您可以使用:
CarrierWave::Mount::Mounter.any_instance.stub(:store!)
通过CarrierWave初始化程序中的简单配置,我将测试套件时间从25秒减少到仅仅2秒:
# config/initializers/carrier_wave.rb CarrierWave.configure do |config| config.enable_processing = false if Rails.env.test? end
此配置会跳过ImageMagick,MiniMagick等的图像处理(resize,裁剪…)。
allow_any_instance_of(CarrierWave::Uploader::Base).to receive(:store!).and_return nil