LoginSignup
2
1

More than 1 year has passed since last update.

Rspecにおける画像検証の方法

Last updated at Posted at 2022-05-13

画像がちゃんと表示されているか検証するテストを書いている時にやり方がわからずハマってしまったので登録のやり方から検証方法までを書いていく。

letで画像を登録する

テストで使用するディレクトリに画像ファイルを置き(例では/spec/factoriesに”image_1.jpg”という画像ファイルを置いている)File.new("#{Rails.root}/画像のパス)でデータを登録する

let!(:user) { create(:user, name: 'user_1', image: File.new("#{Rails.root}/spec/factories/image_1.jpg")) }

フォームに画像を入力する

“attach_file”を使い画像登録の状況を再現する。name属性、ファイルのパス(上の例と同じディレクトリにあるファイルを指定している)を指定することで画像の投稿を再現することができる

attach_file 'フォームのname属性', "#{Rails.root}/spec/factories/image_1.jpg"

画像がimgタグを使って表示されている場合

ユーザーのサムネイル画像などがimgタグでそのまま表示されている場合

expect(page).to have_selector("img[src$='hoge_image.jpg']")

クラスを指定してそのbackground-imageのURLを指定する

画像そのものがimgタグではなくbackground-imageとして表示されている場合の検証方法

expect(page).to have_selector ".class_name[style='background-image: url(#{hoge.image})']"
2
1
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
2
1