Selecting from a dropdown generically with Capybara

For my current project I am developing some smoke tests using Capybara. For smoke tests you want to get from the start to the end of a process without caring too much about the specifics of each page. Additionally, we want to  avoid hardcoding in the tests any data that changes. Otherwise data changes may lead to a misleading test failure (a false positive). In this project there are several dropdowns that contain lists of suppliers, energy plans,  etc. For the smoke test we just want to select a valid option and then move on to the next page.

To help with this I wrote some generic code to choose the second item in a select list – the first item usually being a “please select” message. To do this I use the XPath support in the Capybara API:

def select_second_option(id)
  second_option_xpath = "//*[@id='#{id}']/option[2]"
  second_option = find(:xpath, second_option_xpath).text
  select(second_option, :from => id)
end

The code uses this XPath: //*[@id='#{id}']/option[2] to select the text value of the second option. The standard Capybara API is then used to select that value in the dropdown.

Advertisements

2 comments

  1. Pingback: Capybara roundup
  2. tbbooher · November 26, 2011

    thanks — very useful to get capybara working for me

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s