LoginSignup
13
8

More than 5 years have passed since last update.

[CarrierWave]RSpec実行後の画像ファイルを削除する

Posted at

はじめに

RSpecでテストを何度も実施していたら画像ファイルが膨大に保存されており、自動で削除されるように設定したのでメモします。

参考にしたサイト

How to: Cleanup after your Rspec tests
Rspecのcarrierwaveを実行した後のファイルを削除
画像周りの扱い方
CarrierWave + RSpec ディレクトリ問題

手順

1. 環境

ruby                  : 2.5.1
rails                 : 5.2.2
device                : 4.6.1
carrierwave           : 1.3.1
rspec-rails           : 3.8.2

2. development時とtest時で画像が保存されるディレクトリを分ける

Carrierwaveをインストールした際にrails g uploader Photoをしてapp/uploaders/photo_uoloader.rbが作成されているので、ここに画像の保存場所を設定します。

app/uploaders/photo_uoloader.rb
class PictureUploader < CarrierWave::Uploader::Base
# 省略
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
# 省略

3. テスト終了後にファイルを削除する

spec/rails_helper.rbに以下を追加します。

spec/rails_helper.rb
RSpec.configure do |config|
# 省略
config.after(:all) do
    if Rails.env.test?
      FileUtils.rm_rf(Dir["#{Rails.root}/public/uploads_#{Rails.env}/"])
    end
  end
end
13
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
8