Selecting by Option Value using Capybara

Capybara’s select command allows searching a HTML select field and selecting an option that matches the supplied value by name, id or label text. Additionally, the match option allows the user to indicate the behaviour if more than one option is found. For example, match: :first will select the first item out of multiple matches, while match: :one will throw an error if more than one item is found.

I was recently dealing with a time zone select list based on ActiveRecord::TimeZone. I was receiving an error when Capybara tried to select “Samoa” from the option list (“Samoa” due to test randomisation), since there were items named “American Samoa” and “Samoa”. I ended up having to select the option via its ‘value’ attribute instead:

time_zone = ActiveRecord::TimeZone.all.sample
find('select#time_zone').find("option[value='#{time_zone.name}']").select_option