Rspecについて勉強した時のメモです。
System Specとは
プログラムによってブラウザを操作し想定通りに動作するのかを確認するテストのことです。
system specの具体的な流れは、
①画面が正しく表示されているかを確認したい
②画面の表示に必要なデータの作成
③プログラムによってブラウザが想定通りに表示されているかを確認する
準備
system specはブラウザを操作してテストするのでchromdriverというソフトフェアをインストールする必要があります。
※Google Chromeを元々使用しているのが前提です。
$ brew cask install chromedriver
chromedriver was successfully installed!
と出たらインストール完了です。
実装
前提として前回同様User
がtitle
とcontent
カラムを持つArticle
モデルを投稿できるシンプルなCRUDアプリを想定しています。
テストするフォルダとファイルを作ります
$ mkdir spec/system
$ touch spec/system/article_spec.rb
まずは動作確認がてら簡単なテストを書いていきます。
require 'rails_helper'
RSpec.describe 'Article', type: :system do
it '記事一覧表示' do
visit root_path
end
end
Railsには元々Capybaraというgemがインストールされていて、このCapybaraを使うとRubyでブラウザを操作するためのメソッドを使用できます。
今回のvisit
というのはこのCapybaraから提供されたメソッドで、このvisit
を使うことでプログラムで指定したパスを開いてくれます。
テスト実行
$ bundle exec rspec:spec/system/article_spec.rb
.
Finished in 4.2 seconds (files took 4.26 seconds to load)
1 example, 0 failures
一瞬ブラウザが立ち上がりテスト成功できてればOKです。
ではダミーデータを入れて実際にテストしていきましょう!
have_content
require 'rails_helper'
RSpec.describe 'Article', type: :system do
let!(:user) { create(:user) }
let!(:articles) { create_list(:article, 3, user: user) }
it '記事一覧表示' do
visit root_path
articles.each do |article|
expect(page).to have_content(article.title)
end
end
end
have_content
を使うと今回で言うarticle.title
が存在するかしないかをテストしてくれます。
それをeach
を使って繰り返すことでダミーデータ分全てをテストすることができます。
click_on
click_on
は指定した文字列のaタグをクリックしてくれるメソッドです。
今回はarticle.title
をaタグにしているので、クリックして記事詳細画面へ遷移します。
そして記事詳細ページでtitle
とcontent
がきちんと表示されているかをテストしています。
it '記事詳細表示' do
visit root_path
article = articles.first
click_on article.title
expect(page).to have_css('.article_title', text: article.title)
expect(page).to have_css('.article_content', text: article.content)
end
それではコード全体を確認して、テストしていきましょう!
require 'rails_helper'
RSpec.describe 'Article', type: :system do
let!(:user) { create(:user) }
let!(:articles) { create_list(:article, 3, user: user) }
it '記事一覧表示' do
visit root_path
articles.each do |article|
expect(page).to have_css('.article_title', text: article.title)
end
end
it '記事詳細表示' do
visit root_path
article = articles.first
click_on article.title
expect(page).to have_css('.article_title', text: article.title)
expect(page).to have_css('.article_content', text: article.content)
end
end
記事一覧ページから詳細ページに遷移している挙動を確認できてテストが成功してればOKです。
$ bundle exec rspec:spec/system/article_spec.rb
..
Finished in 4.48 seconds (files took 2.1 seconds to load)
2 example, 0 failures
基礎編は以上です。
次は実際にポートフォリオで実装したテストを解説して行こうと思います!