For the HTML
You could also use capybara-ui which will look first to match the text, then to match the value.
# define your form widget, in this case in a role
class UserRole < Capybara::UI::Role
form :my_form do
select :my_select, 'my_select'
end
end
# then just submit your form params via #submit
role = UserRole.new
role.submit :my_form, my_select: '20120905'
See more about capybara-ui forms here.
That helper method is pretty clever. I would change it just a little bit:
def select_by_value(id, value)
option_xpath = "//*[@id='#{id}']/option[@value='#{value}']"
find(:xpath, option_xpath).click
end
or just:
find(:xpath, "//select[@id='date']/option[@value='20120904']").click
In my case I have a few options with same text, that's the reason why I need select by value. Combining a few answers together I've found the best solution for me:
def select_by_value(id, value)
option_xpath = "//*[@id='#{id}']/option[@value='#{value}']"
find(:xpath, option_xpath).select_option
end
You can also achieve it by doing the following:
find_by_id('date').find("option[value='20120905']").click
I wrote a helper method:
def select_by_value(id, value)
option_xpath = "//*[@id='#{id}']/option[@value='#{value}']"
option = find(:xpath, option_xpath).text
select(option, :from => id)
end
Save in a .rb file in spec/support/
Example use:
before do
select_by_value 'some_field_id', 'value'
click_button 'Submit'
end
This will work to select an option by value:
find("option[value='20120905']").click
To maintain the scope of the selector you could wrap it in a within block as such:
within '#date' do
find("option[value='20120905']").click
end