こんにちは。
腰の痛みを軽減させるためにマッサージ機を当て続けたら痛みが倍増しました。
どうもハチマキです。
はじめに
今回はrspecの振る舞いテストで、下記のようなselectの値が選択されているかというテストを書きたい!けど、エラーが出ました。
ググった結果解消できたので、解決方法について書いていこうと思います。
本日の概要 : セレクトボックスなどの要素を評価したい場合のテスト方法
事象
フォームで入力した値をselectできるようにした時に、expect(page).to have_text('test1')のように書いたら普通にエラーになりました。
原因は単純にtextではないから。でしょうか。
・こんな感じの画面をテストする
エラー例
specファイル
require 'spec_helper' feature 'フォームをテストする', do scenario 'selectの値が表示させる' do fill_in 'test', with: 'hogehoge,fugafuga' click_on '更新' expect(page).to have_text('hogehoge') expect(page).to have_text('fugafuga') end end
ターミナル
Failures: 1) フォームをテストする selectの値が表示させる Failure/Error: expect(page).to have_text('hogehoge') expected to find text "hogehoge" in ~~~~~~~~~~ ... Finished in 32.61 seconds (files took 35.01 seconds to load) 1 example, 1 failure
解決方法
have_xpathを使用し、要素の属性の値を評価するとテストは通ります。
※XPath (XML Path Language) とは:SQLのSELECTのように、条件を指定してXMLデータを取得することができる
specファイル
require 'spec_helper' feature 'フォームをテストする', do scenario 'selectの値が表示させる' do fill_in 'test', with: 'hogehoge,fugafuga' click_on '更新' expect(page).to have_xpath("//option[text()='hogehoge']") expect(page).to have_xpath("//option[text()='fugafuga']") end end
ターミナル
WARNING: The next major version of capybara-webkit will require at least version 5.0 of Qt. You're using version 4.8.7. Top 1 slowest examples (46.21 seconds, 94.3% of total time): selectの値が表示させる Finished in 27.63 seconds (files took 39.55 seconds to load) 1 example, 0 failures