LoginSignup
5
6

More than 5 years have passed since last update.

CarrierWaveを使いつつfixtures + minitestでtestを書く

Last updated at Posted at 2015-10-15

なんかもうちょっといい方法がある気がするんですが、これで一応通りました。

準備

app/models/user.rb
class User < ActiveRecord::Base
  mount_uploader :avatar, AvatarUploader
  validates :avatar, presence: true # ファイルがちゃんと設定されていることを確認
end

やり方

app/uploader/avatar_uploader.rb
class AvatarUploader < CarrierWave::Uploader::Base
  #...
  def store_dir
    return '' if Rails.env.test?
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end
  #...
end
test/fixtures/users.yml
<% file_path = Rails.root.join('test/fixtures/files') %>
user_with_avatar:
  avatar: <%= file_path.join('avatar.png') %>
# test/fixtures/files 配下にavatar.pngを置いておく
test/test_helper.rb
class ActiveSupport::TestCase
  #...
  # Not storing uploads in the tests
  CarrierWave::Mount::Mounter.class_eval { def store!; end }
  CarrierWave.root = Rails.root.join('test/fixtures/files')

  def after_teardown
    super
    CarrierWave.clean_cached_files!(0)
  end
  #...
end
test/model/user_test.rb
class UserTest < ActiveSupport::TestCase
  test 'レコードが作成できること' do
    #...
    file_dir = Rails.root.join('test/fixtures/files/')
    File.open(file_dir.join('avatar.png')) do |image|
      #...
      user.avatar = image
      user.save!
    end
    #...
  end
end

参考記事

Using Rails test fixtures with CarrierWave

5
6
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
5
6