15
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Capybara + rspec で selected の状態を判定する : Rails

Last updated at Posted at 2015-09-14

次のように書く。

expect(page).to have_select('book[id]', selected: 'ソフィーの世界')

テストの例。

spec/features/selected.rb
require 'spec_helper'

feature '/books', type: :feature do
  before do
    visit book_path
    select 'ソフィーの世界', from: 'book[id]' #いちど選択状態にする
  end

  scenario "要素が選択状態になっている" do
    expect(page).to have_select('book[id]', selected: 'ソフィーの世界') # 選択状態を判定する
  end
end
app/views/books/index.html
<select id="book" name="book[id]">
  <option>我輩は猫である</option>
  <option>ソフィーの世界</option>
  <option>ガリバー旅行記</option>
</select>

#ポイント

  • Capybaraは「外側から見えた状態」を判定するので、<option vallue=""> の値ではなく、 <option></option> の中身(ユーザーに見えるテキスト)を検証する。
  • have_select / select に渡すのは <select id=""> の値でも、<select name=""> の値でも良い。どちらかを勝手に探してくれる。( 1ページ内に、name と id で同名があるとエラーが起こるので注意。id / name のどちらかを明示する方法はないっぽい )
  • なので本当はこちらのように、 <label for=""></label> のテキストで指定した方が良いと思う。
  • have_select は selected を直接判定するマッチャではない。<select></select> 全体の状態を判定する。だから selected を判定するために、オプションで selected: を指定する。

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

メンター受付

15
13
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
15
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?