6
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

updated at

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

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

準備

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

Register as a new user and use Qiita more conveniently

  1. You can follow users and tags
  2. you can stock useful information
  3. You can make editorial suggestions for articles
What you can do with signing up
6
Help us understand the problem. What are the problem?