Capybara, selecting 1st option from dropdown?

2019-07-08 16:32发布

I've done a search and most of the related google results have returned just in general selecting an element from a dropdown. However the ID's in this case for the elements in the dropdown are dynamically generated unfortunately.

This is for a base test case, so I basically just need to select for example the first one. The text is also the same for the elements in the dropdown (not sure if that helps).

Is there such an example of this?

Im using cucumber with caybara(using selenium driver) integration

3条回答
爷的心禁止访问
2楼-- · 2019-07-08 17:10

After two days of searching and reading, this article was amongst one of a few that was helpful. Hopefully, this can help someone else!

I created a few methods like so, excuse the naming..I changed it.

def some_dropdown(id, text)
  dropdown = find(id).click
  dropdown.first('option', text: text).select_option
end

def select_form
  within 'content#id' do
    some_dropdown('#id', text)

    click_link_or_button 'Submit'
  end
end

I also referenced this.

查看更多
唯我独甜
3楼-- · 2019-07-08 17:19

You can find the first option element and then use the select_option method to select it.

For example, if the select list has an id "select_id", you can do:

first('#select_id option').select_option

As @TomWalpole mentions, this will not wait for the element to appear. It would be safer to do one of the following:

first('#select_id option', minimum: 1).select_option

or

find('#select_id option:first-of-type').select_option
查看更多
做自己的国王
4楼-- · 2019-07-08 17:34

Alternatively you can get the first element text then select it by select function:

first_element = find("#id_of_dropdown > option:nth-child(1)").text
select(first_element, :from => "id_of_dropdown")
查看更多
登录 后发表回答