LoginSignup
5
12

More than 3 years have passed since last update.

Rails RSpec による画像添付結合テスト

Posted at

はじめに

RSpecによるオリジナルアプリの結合テストを行っています。画像投稿機能において、「テスト用の画像を添付する」、「添付したテスト用の画像が画面上にあるか」の2つを忘れていたので、備忘録として書き記します。

#目次
1.テスト用の画像を添付する
2.添付したテスト用の画像が画面上にあるかテストする

1.テスト用の画像を添付する

ここではimage_pathという変数にテスト用画像(test_image.jpg)を添付する。この時相対パスで指定する。
attach_fileメソッドはアップロードのinput要素にテスト用画像を添付することができる。第一引数にアップロードするinput要素のname属性の値、第二引数にアップロードする画像のパス、第三引数にオプション(ここではmake_visible: trueで一時的に表示)を設定する。

spec/system/◯◯_spec.rb
# 添付する画像を定義する
image_path = Rails.root.join('public/images/test_image.jpg')

# 画像選択フォームに画像を添付する
attach_file('desk[image]', image_path, make_visible: true)

2.添付したテスト用の画像が画面上にあるかテストする

画像を投稿すると、画像一覧ページに遷移する。遷移先で投稿した画像があるかの確認は下記コードに記す。have_selectorで要素があるか判断する。ちなみにhave_content()で文字列があるかのマッチャになる。

spec/system/◯◯_spec.rb
expect(page).to have_selector("img[src$='test_image.jpg']")

以上

5
12
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
5
12