I'm a Ruby beginner who creates a portfolio with Ruby on Rails. I think that there are many people who have implemented the image upload function in CarrierWave. I am also one of them. This gem is used for user avatar settings and image attachment when posting, and the image upload function of CarrierWave was included for confirmation in various tests.
While creating the portfolio, after running the test several times, when I happened to look at the folder where the images are saved ... ** The number of folders is 600! ?? ** **
I didn't notice it at all. The more you turn the test, the more the images included in the test case will be uploaded over and over again. Before I knew it, my folder was tight with image capacity ...
You can turn it off manually, but the tests are done with each refactoring or feature addition, which is quite annoying. So, ** I will set it to erase the image of CarrierWave created for the test ** after running the test.
I am developing rails by creating a container in Docker.
Docker for mac 2.3.0.4
Ruby on Rails 5.2.2
ruby 2.4.5
CarrierWave 2.1.0
I referred to the following page on the CarrierWave wiki How to: Cleanup after your Rspec tests
While referring to this, delete it according to the following flow. ** 1. Specify the upload folder for test (uploeader file) ** ** 2. Clear all folders with the specified path after running the rspec test **
** 1. Specify upload folder during test ** Since some cache files are also generated (during error check test cases) Specify both cache and store folders.
app/uploaders/***_uploader.rb
:
#Specify cache folder
def cache_dir
if Rails.env.test?
"uploads/#{Rails.env}/tmp/#{mounted_as}/#{model.id}"
else
"uploads/tmp/#{mounted_as}/#{model.id}"
end
end
#Specify the folder of store
def store_dir
if Rails.env.test?
"uploads/#{Rails.env}/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
else
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
end
:
** 2. Clear all folders in the specified path after running the rspec test ** Write the path to delete the cache and store folder specified above at once.
spec/spec_helper.rb
:
config.after(:all) do
if Rails.env.test?
FileUtils.rm_rf(Dir["#{Rails.root}/public/uploads/#{Rails.env}/"])
end
end
:
This will automatically clear the test folder every time you run the rspec test.
I've run the test many times and now I don't have a lot of folders or tight space, Impression that the processing speed of rspec has slowed down a little because the process of erasing has entered the test. This can't be helped, but it's a good idea to tell if you really need image uploads during the test, and if not, consider creating factories without images. I would also like to review the test cases.
Recommended Posts