paperclipで画像アップロードを含めたテストをfactory_girlを使ってテストする
先日paperclipをバージョン4にアップデートしたら、今まで通っていたテストが失敗した。
ので、factory_girlを使っている場合、どう書くのが良いのか調べた。
まずpaperclipを4にしてからcontent_typeのチェックを行うバリデーションをhas_attached_fileの後に定義する必要があるようで、やりました。
で、そこまでやって再度テスト実行しましたが、バリデーションチェックにかかり駄目でした。
調べた結果fixture_file_uploadというメソッドを使うとよいそうだったので、対応しました。
そうしたらテストも通るようになった。
やったー!以下ソース
まずはfactory_girlを使ってテストデータを作成
1 # Read about factories at https://github.com/thoughtbot/factory_girl 2 3 include ActionDispatch::TestProcess 4 5 FactoryGirl.define do 6 factory :current_user_photo1, class: Photo do 7 title "test photo" 8 sequence(:description) { |n| "MyText#{n}" } 9 photo_file_name "MyString" 10 photo_content_type "MyString" 11 photo_file_size 1 12 photo { fixture_file_upload([Rails.root, "spec", "factories", "test.png"].join("/"), "image/jpg") } 13 end 14 15 end
続いてモデルです。
class Photo < ActiveRecord::Base has_attached_file :photo, default_url: "/images/:style/missing.png", styles: { medium: "350x350>", thumb: "100x100>", original: "700x700>" } validates_attachment :photo, :presence => true, :content_type => { :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif" ] }, :size => { :in => 0..10000.kilobytes } end
次にテストコードです。
describe Photo do 20 21 let!(:test_group) { FactoryGirl.create(:current_user_group1) } 22 let!(:test_user1) { FactoryGirl.create(:current_user) } 23 let!(:auth_provider1) { FactoryGirl.create(:current_user_auth_provider, user: test_user1) } 24 let!(:test_album) { FactoryGirl.create(:current_user_album1, user: test_user1, group: test_group) } 25 let!(:photo1) { FactoryGirl.create(:current_user_photo1, user: test_user1, album: test_album) } 26 let!(:photo2) { FactoryGirl.create(:current_user_photo1, user: test_user1, album: test_album) } 27 let!(:photo3) { FactoryGirl.create(:current_user_photo1, user: test_user1, album: test_album) } 28 let!(:photo4) { FactoryGirl.create(:current_user_photo1, user: test_user1, album: test_album) } 29 let!(:photo5) { FactoryGirl.create(:current_user_photo1, user: test_user1, album: test_album) } 31 describe "save photo test" do 32 33 it { expect belong_to(:album) } 34 35 context "photo 投稿" do 36 before do 37 @file = File.new("spec/factories/test.png") 38 @file.binmode 39 @subject = Paperclip.io_adapters.for(@file) 40 @photo = Photo.new(title: "test photo", description: "これはテストです", user_id: test_user1.id, album_id: test_album.id, photo: @subject) 41 end 42 43 # it "photo save success" do 44 # expect(@photo.save).to be_truthy 45 # end 46 47 it "database check" do 48 @photo.save 49 saved_photo = Photo.where(title: 'test photo').first 50 expect(saved_photo).not_to be_nil 51 expect(saved_photo.title).to eql('test photo') 52 @album = test_album 53 expect(@album.photos).not_to be_nil 54 expect(@album.photos.size).to eql(5) 55 end 56 57 it "album top image" do 58 @photo.save 59 @album = test_album 60 expect(@album.top_img_path).not_to be_nil 61 end 62 end end end
以上ですー。これでテストが全件通る!!