LoginSignup
4
5

More than 3 years have passed since last update.

【RSpec】toggleされた要素へのクリック対応

Posted at

はじめに

RSpecでユーザー登録の統合テストをかいているときに、
toggleされた要素に対するクリックのやり方でつまづきました。
僕と同じ初学者の方の参考になりましたら幸いです。

RSpecでのテスト

RSpecでの簡単なテストを一部抜粋。
ルートページで「新規登録」ボタンをおすと、
「ユーザーの新規登録」と記載されているページに遷移することを確認するテスト。

it 'ユーザー登録ページが表示される' do
  visit root_path
  click_on '新規登録'
  expect(page).to have_content 'ユーザーの新規登録'
end

下記エラーが発生。

Failure/Error: click_on '新規登録'

     Capybara::ElementNotFound:
       Unable to find visible link or button "新規登録"

slimには=link_to signup_path, class: 'nav-link' do | 新規登録のコードがあり、
ブラウザでページを表示させても「新規登録」ボタンは確かにあるのに、上記エラーが発生。

Bootstrapのtoggleが原因

テスト用のブラウザでは「新規登録」ボタンがtoggle化されていたため、
エラーが発生していた。

試しに、下記のように内容を変更してみる。

it '新規登録ボタンの確認' do
  visit root_path
  expect(page).to have_content '新規登録'
end
Failure/Error: expect(page).to have_content '新規登録'
       expected to find text "新規登録" in (略).
 (However, it was found 1 time including non-visible text.)

「non-visible text」としては「新規登録」があるとの指摘。

対応

toggleのアイコンをクリックするステップを入れる。

it 'ユーザー登録ページが表示される' do
  visit root_path
 find(".navbar-toggler-icon").click
  click_on '新規登録'
  expect(page).to have_content 'ユーザーの新規登録'
end

これで解決。

 

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