22時に寝ようと思って2時に寝る。

備忘録や日記を書いてます。きょうは早く寝よう。

RSpec - テストでは画像アップローダを無効にする

Cloudinary::CarrierWave::UploadError

現在開発しているRailsアプリでは、Userのプロフィール画像をCarrierWaveを用いて、Cloudinaryに画像をアップロードする方法で実装しています。 このUserモデルに関わるテストを行うときはFactoryGirlを用いてテストデータを用意しています。

FactoryGirl.define do
  factory :user do
    sequence(:email) { |i| "#{i}_#{Time.current.to_i}_#{Faker::Internet.email}" }
    name Faker::Name.name
    profile Faker::Lorem.sentence
    password "userpassword"
    user_image { fixture_file_upload Rails.root.join('spec/fixtures/files/sample_500x500.png'), 'image/png' }
  end
end

この状態で、テストを実行すると、以下の結果になります。(一部抜粋)

Failures:

  1) Articles GET /api/v1/articles 記事一覧を取得する パラメータを指定しない
     Failure/Error: let!(:articles) { create_list(:article, 3) }

     Cloudinary::CarrierWave::UploadError:
       cloud_name is disabled
     # ./spec/requests/articles_spec.rb:6:in `block (4 levels) in <top (required)>'

Finished in 3.73 seconds (files took 11.97 seconds to load)

今回、テストで画像に対して複雑なテストをするわけでもないため、Cloudinaryの画像をアップロードするロジックは噛ませる必要がありません。 そのため以下の解決方法をとりました。

config.enable_processing = false if Rails.env.test?

config/initializers/carrier_wave.rbを作成し、以下を記述します。

CarrierWave.configure do |config|
  config.enable_processing = false if Rails.env.test?
end

こうすることで、テスト環境に限りアップロード処理をスキップすることができ、テストも無事、通るようになります。

.

Finished in 2.7 seconds (files took 7.97 seconds to load)
1 examples, 0 failures

以上です。

参考

stackoverflow.com