0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【rspec】画像のテスト

Posted at

rspecでの画像の投稿とその表示

rspecでの画像の投稿をする場合、Active Storageを使用する。

Active Storageとは
Amazon S3、Google Cloud Storage、Microsoft Azure Storageなどのクラウドストレージサービスへのファイルのアップロードや、ファイルをActive Recordオブジェクトにアタッチする機能を提供します。 development環境とtest環境向けのローカルディスクベースのサービスを利用できるようになっており、ファイルを下位のサービスにミラーリングしてバックアップや移行に用いることも可能です。

Active Storageは、アプリケーションにアップロードした画像の変形や、PDFや動画などの画像以外のアップロードファイルの内容を代表する画像の生成、任意のファイルからのメタデータ抽出にも利用できます。

Active Storageセットアップ

Active Storageのセットアップをしていく。

config/storage.yml
test:
  service: Disk
  root: <%= Rails.root.join("tmp/storage") %>

画像のセット、画像選択

spec/fixturesファイルを作成し、配下に画像をセットしておく。

require 'rails_helper'

RSpec.describe 'AddState', type: :system do
    let(:admin) { create :user, :admin }
    let!(:article) { create :article}

    before do
        login(admin)
        visit admin_articles_path
        click_on '編集'
        attach_file 'article[eye_catch]', "#{Rails.root}/spec/fixtures/sample.jpg"
        click_on '更新する'
    end

    describe 'アイキャッチの横幅を変更' do
     context '横幅を100~700pxに指定した場合' do
       it '記事の更新に成功し、プレビューでアイキャッチが確認できる' do
        eyecatch_width = rand(100..700)
        fill_in 'article[eyecatch_width]', with: eyecatch_width
        click_on '更新する'
        click_on 'プレビュー'
        switch_to_window(windows.last)
        expect(page).to have_css('.eye_catch')
        expect(page).to have_selector("img[src$='sample.jpg']")
       end
     end
   end

      describe 'アイキャッチの位置' do
      it '左寄りにした場合、正常に左寄せに表示される' do
        choose '左寄せ'
        click_on '更新する'
        click_on 'プレビュー'
        switch_to_window(windows.last)
        expect(page).to have_selector('section.eye_catch.text-left')
      end
   end
end

attach_file 'article[eye_catch]', "#{Rails.root}/spec/fixtures/sample.jpg"
attach_fileにてファイルアップロードしているため、ここで画像を指定している。

eyecatch_width = rand(100..700)
100~700の間の数値をランダムでeyecatch_widthに代入している。

expect(page).to have_selector("img[src$='sample.jpg']")
画像の位置と画像が表示されているか判定している。

expect(page).to have_selector('section.eye_catch.text-left')
画像が中央位置にあるか判定している。

参考記事

Active Storageについて
【RSpec】画像の登録と表示についてテストする

0
2
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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?