LoginSignup
17

More than 5 years have passed since last update.

locatorで指定しづらいradio buttonを操作する方法

Posted at

HTML中に以下のようにradio buttonが並んでいるとします。

<input type="radio" name="fruit" value='apple'> リンゴ
<input type="radio" name="fruit" value='orange'> オレンジ
<input type="radio" name="fruit" value='strawberry'> イチゴ

これをRSpecなどでCapybara使ってどうやって選ぶかなのですが、適切にlabelが指定されていればchooseでいけるものの、上記例のようにlabelが設定されていない場合chooseでは難しそうです。このメソッドは引数にcssやxpathを付けつけてくれないようだからです。

そこで、choose自体はCapybara::Node::Elementに対して何かしらの操作をしているだけだろうと予想し、Capybara::Node::Actionsのドキュメントを読んでchooseがCapybara::Node::Elementをどういじっているのかを見てみました。

# File 'lib/capybara/node/actions.rb', line 65

def choose(locator, options={})
  find(:radio_button, locator, options).set(true)
end

findはcssでもxpathでもなんでも受け付けてくれます。ということで、上記の例でいえば

find("input[name='fruit'][value='apple']").set(true)

でリンゴ用のradio buttonをチェックすることができます。なお、check box用のcheckも同様にいけるようです。

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
17