水豚,从下拉列表中选择第一个选项?

Capybara, selecting 1st option from dropdown?

我进行了搜索,大多数相关的 google 结果一般都返回 select 下拉列表中的一个元素。然而,不幸的是,在这种情况下,下拉列表中的元素的 ID 是动态生成的。

这是一个基本测试用例,所以我基本上只需要 select 例如第一个。下拉列表中的元素的文本也是相同的(不确定是否有帮助)。

有这样的例子吗?

我正在使用 Cucumber 与 caybara(使用 selenium 驱动程序)集成

您可以找到第一个选项元素,然后使用 select_option 方法 select 它。

例如,如果 select 列表有一个 id "select_id",你可以这样做:

first('#select_id option').select_option

正如@TomWalpole 提到的,这不会等待元素出现。执行以下操作之一会更安全:

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

find('#select_id option:first-of-type').select_option

或者,您可以通过 select 函数获取第一个元素文本,然后 select 它:

first_element = find("#id_of_dropdown > option:nth-child(1)").text
select(first_element, :from => "id_of_dropdown")

经过两天的搜索和阅读,这篇文章是为数不多的有帮助的文章之一。希望这可以帮助其他人!

我创建了几个这样的方法,请原谅命名..我改变了它。

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

我也参考了this

我试过 select 模式下拉菜单中的一个选项。在尝试了所有列出的方法以及其他线程中的许多其他方法之后 - 我完全放弃了,而不是使用 clicksselect_option 只是使用键盘按键

find(:select, "funding").send_keys :enter, :down, :enter

万一它仍然抱怨 - 尝试:

find(:select, "funding", visible: false).send_keys :enter, :down, :enter

工作得很好,select从下拉列表中选择第一个选项。