Skip to content

How to: Cleanup after your Rspec tests

Matijs van Zuijlen edited this page Jun 2, 2015 · 8 revisions

If you are running tests that generate attachments, you can use an after(:all) callback in Rspec to do some cleaning up. The actual cleanup code will vary based on your setup, but here is an example:

RSpec.configure do |config|
  # ...
  config.after(:all) do
    # Get rid of the linked images
    if Rails.env.test? || Rails.env.cucumber?
      tmp = Factory(:brand)
      store_path = File.dirname(File.dirname(tmp.logo.url))
      temp_path = tmp.logo.cache_dir
      FileUtils.rm_rf(Dir["#{Rails.root}/public/#{store_path}/[^.]*"])
      FileUtils.rm_rf(Dir["#{temp_path}/[^.]*"])
      # if you want to delete everything under the CarrierWave root that you set in an initializer,
      # you can do this:
      # FileUtils.rm_rf(CarrierWave::Uploader::Base.root)
    end
  end
end

Please Note - the above code assumes that the store_path and cache_dir paths are separated based on the Rails environment. DO NOT just copy and paste that into your spec_helper file unless you understand and have accounted for that. Otherwise you may end up deleting production files too. As an example, you can configure your paths per environment as such:

class MyUploader < CarrierWave::Uploader::Base
  def cache_dir
    "#{Rails.root}/tmp/uploads/#{Rails.env}/brands/logos"
  end
  
  def store_dir
    "system/attachments/#{Rails.env}/brands/logos/#{model.friendly_id}/"
  end
end

If you want to separate uploader folders with only test environment, you can override uploader methods (:cache_dir, :store_dir). As a example, you see following:

# spec_helper.rb
RSpec.configure do |config|
  # ...

  config.after(:all) do
    if Rails.env.test? 
      FileUtils.rm_rf(Dir["#{Rails.root}/spec/support/uploads"])
    end 
  end 
end
# put logic in this file or initializer/carrierwave.rb
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

https://gist.github.com/1382625

If you don't want to mess with your uploaders' store_dir, you can also override root instead.

Clone this wiki locally