【问题标题】:Capybara - how to see if a dropdown element is selected?Capybara - 如何查看是否选择了下拉元素?
【发布时间】:2016-02-22 00:40:07
【问题描述】:

我的 HTML 是

<select id="auto_policy_autos_attributes_0_ownership" name="auto_policy[autos_attributes][0][ownership]">
  <option value="Owned">Owned</option>
  <option value="Financed">Financed</option>
  <option value="Leased" selected="selected">Leased</option></select>

我最多可以选择

find('select#auto_policy_autos_attributes_0_ownership option[value="Leased"]')

正确,但是如何查看是否已检查?

我试过了

find('select#auto_policy_autos_attributes_0_ownership option[value="Leased" selected="selected"]')

但我明白了

Selenium::WebDriver::Error::InvalidSelectorError: invalid selector: 
An invalid or illegal selector was specified

我有希望

'select#auto_policy_autos_attributes_0_ownership option[value="Leased"], selected')).to be

但我得到一个误报

'select#auto_policy_autos_attributes_0_ownership option[value="Owned"], selected')).to be

返回 true,即使我选择了 Leased with

select 'Leased', from: 'auto_policy_autos_attributes_0_ownership'

我可以在浏览器中看到。

【问题讨论】:

    标签: selenium drop-down-menu webdriver capybara html-select


    【解决方案1】:

    您可以使用be_selected matcher:

    expect(@session.find('select#auto_policy_autos_attributes_0_ownership option[value="Leased"]')).to be_selected
    

    【讨论】:

      【解决方案2】:

      一个选项是

      expect(has_select?('auto_policy_autos_attributes_0_ownership', selected: 'Leased')).to be true
      

      【讨论】:

      • 但我更喜欢 alecxe,因为 be_selected 更具描述性,尤其是当它失败时(当它很重要时!)
      【解决方案3】:

      这正是 capybara have_select 匹配器的设计目的

      expect(page).to have_select('auto_policy_autos_attributes_0_ownership', selected: 'Leased')
      

      它描述了您正在检查的内容 - 具有特定选择选项的特定选择元素,并在发生故障时提供了一个很好的错误消息。

      如果你真的想坚持使用谓词匹配器,你也可以这样做

      expect(find(:option, 'Leased')).to be_selected 
      

      尽管该选项可以在页面上的任何选择中,除非您使用了一个内块或将查找范围限定为特定选择。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-04-14
        • 1970-01-01
        • 1970-01-01
        • 2011-05-07
        • 2021-08-31
        • 1970-01-01
        • 2023-03-13
        相关资源
        最近更新 更多