Select 使用 Capybara 的 select2 跨度

Select span for select2 using Capybara

我正在尝试编写一个允许我使用自定义 select2 country_search 元素的自定义方法。元素有点不稳定,但 HTML 的片段看起来像这样:

<div class="control-group select optional admins_customer_form_object_country_id">
  <label class="select optional control-label" for="admins_customer_form_object_country_id">Country</label>
  <div class="controls">
    <select id="admins_customer_form_object_country_id" class="select optional select2-hidden-accessible" name="admins_customer_form_object[country_id]" tabindex="-1" aria-hidden="true">
      <option value=""></option>
      <option value="true">Yes</option>
      <option value="false">No</option>
    </select>
    <span class="select2 select2-container select2-container--classic select2-container--below select2-container--focus" dir="ltr" style="width: 220px;">
      <span class="selection">
        <span class="select2-selection select2-selection--single" role="combobox" aria-autocomplete="list" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-labelledby="select2-admins_customer_form_object_country_id-container">
          <span class="select2-selection__rendered" id="select2-admins_customer_form_object_country_id-container">
            <span class="select2-selection__placeholder">Select Country</span>
          </span>
          <span class="select2-selection__arrow" role="presentation">
            <b role="presentation"></b>
          </span>
        </span>
      </span>
      <span class="dropdown-wrapper" aria-hidden="true"></span>
    </span>
  </div>
</div>

我写了一个帮助程序,它应该 select 正确 span 并点击它,但我无法 select 达到我想要的范围。我正在尝试 select 具有 class select2 select2-container select2-container--classic select2-container--below select2-container--focus 的外部可见范围,但我不断收到无效的 XPath 错误。

这是我目前拥有的:

def select_country(label:, value:)
  # Select our label first
  label_element = first("label", text: label)

  # Now navigate through the entire tree, and click the correct SPAN element.
  within(label_element) do
    select2_container = find(:xpath, "..")  # Up one level to the parent div
    select2_container = select2_container.find("div.controls")  # Down one level into the div.container
    select2_container = select2_container.find(:xpath, "./*[1]")  # select the span element surrounding all.
  end
end

在最后一行中,我可以 select 树中的 select 元素,但无论如何我都无法获得 span 兄弟元素。

如果我没看错,你想要 div.controls 的子跨度,用以下内容替换最后两个发现应该做到这一点

select2_container = select2_container.find('div.controls > span')

如果需要,您可以将 类 添加到 css 选择器中的跨度,但在您的 html 中,它是唯一的跨度子级,因此没有必要