LoginSignup
29
35

More than 1 year has passed since last update.

paperclipでファイルアップロードをRspecでテスト w/ factory_girl

Last updated at Posted at 2015-05-06

次ブログから要旨だけ抽出:http://konyu.hatenablog.com/entry/2015/05/05/155421

動作確認環境

  • OSX yosemite
  • Ruby2.2.0
  • Rails4.2
  • Rspec3.1

準備 設定ファイル修正rails_helper.rb

fixture_file_uploadを呼び出せるように、ライブラリを読み込むように追記

追記箇所は以下のようにRSpec.configureのブロック内に追記

RSpec.configure do |config|
  ...
  ..
  # paperclip file uploadテスト用
  # rspec内で、ファイルアップロードのテストに使用する
  config.include ActionDispatch::TestProcess

  # factoryGirl内での呼び出し
  FactoryGirl::SyntaxRunner.class_eval do
    include ActionDispatch::TestProcess
  end

  # fixtureのパス指定
  # ファイルアップロードテストする際のアップするファイルを指定するパスをfixtures以下から省略して指定
  config.fixture_path = "#{::Rails.root}/spec/fixtures"

end

ファイルアップロードのテスト

アップロード対象のファイルを置く

fixture_pathを通してある/spec/fixturesの下にアップロード対象のファイルを置く
今回の説明では/spec/fixtures/voice/voice01.mp3を設置する

※ ダミーのテキストファイルの拡張子を変えただけのファイルだと怒られる

アップロードするメソッドの呼び出し方

# 呼び出し方
fixture_file_upload("相対パスのファイル名", "mime_type"))
# mp3の場合
fixture_file_upload("voice/voice01.mp3", "audio/mp3"))  

具体的なRspecコード例

describe "#update a and file upload" do
  it "can upload with update_attributes" do
    # sound モデルを更新してファイルをアップロードする
    sound.update_attributes(voice: fixture_file_upload("voice/voice01.mp3", "audio/mp3"))
    sound.reload
    # paperclipで生成されたファイル名を格納したカラムに値が入っていることを確認
    expect(sound.voice_file_name).not_to be_nil
 end
end

Factory_girlのフィクスチャでファイルをアップロード済みのモデルと定義する場合

factory_girlの定義

factory :sound do
  msg "original"
  trait(:recorded) do
    # factory_girlのファイルではfixture_pathを見てくれないので頭からパスを定義して上げる必要があった。
    voice { fixture_file_upload("#{::Rails.root}/spec/fixtures/voice/voice01.mp3", "audio/mp3") }
  end
end 

specファイルで呼び出し例

let(:sound) { FactoryGirl.create(:sound, :recorded) }

ref:http://apidock.com/rails/ActionController/TestProcess/fixture_file_upload

29
35
1

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
29
35