LoginSignup
3
4

More than 1 year has passed since last update.

【Capybara,webdrivers】統合テスト(System Spec)とは

Last updated at Posted at 2022-01-31

統合テスト(System Spec)とは

統合テストは、アプリケーション全体が一つのシステムとして期待通りに動くか否かを検証するテストのこと。

統合テストにおいては、Capybaraというrubyのライブラリを使用。Capybaraを使うことで、実際のアプリケーションの使われ方をコードで表すことができる。(fill_inclick_buttonなど)

webdriversChromeDriverを簡単に導入してくれるgemである。アプリケーション全体が一つのシステムとして期待通りに動くか否かを検証する場合、実際にブラウザでテストがそうのように動いているのか目視できた方が分かりやすいので、Capybarawebdriversはセットで入れることが多い。

Capybarawebdriversの導入を記載していく。

gemの導入

Gemfile.
group :test, :development do
  # (省略)
  gem 'capybara'
  gem 'webdrivers'
end

bundle install後、spec/rails_helper.rbに下記の一文を追記。

spec/rails_helper.rb
require 'capybara/rspec'  #追記

Capybara.configure do |config|
---省略---
end

webdriversの設定

spec/supportディレクトリ下にcapybara.rbを作成し、下記を追記。

spec/support/capybara.rb
RSpec.configure do |config|
    config.before(:each, type: :system) do
        driven_by :selenium, using: :headless_chrome #←ブラウザの表示無
       #driven_by :selenium_chrome ←ブラウザの表示有
    end
end

chromeについての設定を記入している。ここでheadless_chromeと記入されている一文を表記すればブラウザの表示を無しにできる。
逆に、コメントアウトされている方を記載すると、ブラウザの表示有になる。

注意
テストファイルを作成した際、おそらくデフォルトで下記のようになっている。

example_spec.rb
require 'rails_helper'

RSpec.describe 'Tasks', type: :system do
before do
driven_by(:rack_test)
end

pending "add some scenarios #{__FILE__}"
#↑この1文はRSpecの書き方を解説している。削除してOK
end

driven_byで実行時のブラウザを指定しているので、この記載を削除。(spec/support/capybara.rbでブラウザの指定を一元管理しているため)

【Capybara】要素を操作するメソッド

メソッド 動作
visit ページへアクセスする(GETリクエスト)
check チェックボックスをチェックする
uncheck チェックボックスのチェックを外す
fill_in テキストフォームに入力する
select セレクトボックスを選択する
choose ラジオボタンを選択する
attach_file ファイルセレクタにファイルを設定する
click クリックを実行する
click_on ボタンorリンクをクリックする(click_button/click_link)
accept_alert アラートのボタンをクリックする
switch_to_window(windows.last) 最後に開いたタブに移動
page.driver.browser.switch_to.alert.accept アラートウインドウの「OK」ボタンを押す
page.driver.browser.switch_to.alert.dismiss アラートウインドウの「キャンセル」ボタンを押す
have_selector 特定のタグやCSS要素に特定の文字列が表示されているかを検証

実用例

tasks_spec.rb
equire 'rails_helper'

RSpec.describe 'Tasks', type: :system do
  let(:user) { create(:user) }
  let(:task) { create(:task) }

  describe 'タスク削除' do
      let!(:task) { create(:task, user: user) }

      it 'タスクの削除が成功する' do
        visit tasks_path
        click_on "Destroy"
        expect(page.accept_confirm).to eq 'Are you sure?'        
        expect(page).to have_content "Task was successfully destroyed"
        expect(current_path).to eq tasks_path
        expect(page).not_to have_content task.title
      end
    end
  end
end

参考記事

【Rails】Capybaraを使った統合テスト(導入〜簡単なテスト実行まで)
【Rspec】統合テスト(System Spec)について
Rspecの設定(SystemSpecの導入、実行時にブラウザ表示、非表示の切り替え設定) #5
Capybaraと仲良くなる(タブ・ウィンドウの操作について)

3
4
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
3
4