ruby-on-railsrspeccarrierwavespork

Carrierwave store_dir not modified when running rspec with spork


I've followed the instructions on how to define a test-specific store directory for carrierwave uploads, which suggests opening the CarrierWave::Uploader::Base class and redefining store_dir and cache_dir like so:

if defined?(CarrierWave)
  CarrierWave::Uploader::Base.descendants.each do |klass|
    next if klass.anonymous?
    klass.class_eval do
      def cache_dir
        "#{Rails.root}/spec/support/uploads/tmp"
      end 

      def store_dir
        "#{Rails.root}/spec/support/uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
      end 
    end 
  end
end

This works like a charm, except when I run rspec with spork, then it fails to modify the class and uploads are stored in the default location. Does anyone have any clue why this might be happening?


Solution

  • Someone else working on our project solved this problem by adding a line with just AvatarUploader ahead of the CarrierWave::Uploader::Base.descendants.each line, like this:

    if defined?(CarrierWave)
      AvatarUploader # load AvatarUploader class 
      CarrierWave::Uploader::Base.descendants.each do |klass|
      #...
    

    Not entirely sure why this works, but it does.