forked from carrierwaveuploader/carrierwave
-
Notifications
You must be signed in to change notification settings - Fork 2
How to: Cleanup after your Rspec tests
Janko Marohnić edited this page Jul 8, 2013
·
5 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}/[^.]*"])
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 past 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