LoginSignup
14
12

More than 5 years have passed since last update.

Cucumber + Capybara + Poltergeistを使って別タブで開くリンクのテスト

Posted at

CucumberとCapybaraとPoltergeistを使ってテストをしていたときに、
別タブで開くリンク(target="_blank"となっているリンク)のテストで引っかかった。

別タブで開くリンクのクリック

target="_blank"となっているリンク(ボタン)を
click_buttonclick_linkclick_onを使ってクリックしたところ
TimeoutErrorが発生した。

teampoltergeist/poltergeistを読んでみると

If you can't figure out what's going on and just want to work around the problem so you can get on with life, consider using a DOM click event. For example, if this code is failing:
click_button "Save"
Then try:
find_button("Save").trigger('click')

と書かれていたので、

find_button("button").trigger('click')

のように書き換えたらタイムアウトしなくなった。

また、テストするページを別タブへ切り替える方法はwithin_windowメソッドを使用して

handle = page.driver.browser.window_handles.last
page.driver.browser.within_window(handle) do
  # 別タブ内で実行したい処理を書く
end

のように書く。

出来れば「タブを切り替える」操作を処理内容と切り離したいというひとは
switch_toメソッドを使うと良い。

Seleniumであれば、switch_toメソッドが使えるが、
Poltergeistの現時点のgem(1.5.1)ではswitch_toメソッドに対応していない。
teampoltergeist/poltergeistのmasterでは対応しているらしい。

(おまけ)CucumberでSimple-Covを使用する

本題とは関係ないが、メモ。
Simple-Covをインストールして、env.rbに下記を加える。

features/support/env.rb
require 'simplecov'

SimpleCov.start

これでテスト実行時に、カバレッジが表示されるようになる。

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