如何从名称中带有变量的 selection box select?
How to select from a selection box with a variable in the name?
我在使用来自这个 select 元素的 selecting 时遇到问题。
<select name="vehicle_attrs[position_count]" class="mb1"><option>Position / Quantity</option><option>Front</option><option>Rear</option></select>
我试过了
select('Front', :from=>'mb1')
select('Front', :from=>'vehicle_attrs[position_count]')
select('Front', :from=>'vehicle_attrs[1]')
全部导致找不到selection box错误
从 select
的文档 - https://www.rubydoc.info/github/teamcapybara/capybara/Capybara/Node/Actions#select-instance_method - 我们可以看到 from
选项采用 "The id, Capybara.test_id atrtribute, name or label of the select box"。
'mb1' 或 'vehicle_attrs[1]' 都不是这些,因此预计它们会失败。
'vehicle_attrs[position_count]' 是名称,所以假设该框在页面上实际上是可见的(没有替换为 JS 驱动的 select 小部件等),那应该可以工作。如果没有,请编辑您的问题并添加您在尝试使用它时收到的完整错误消息。当然,如果页面上只有一个 select 框带有 'Front' 选项,那么您根本不需要指定 from
选项,只需执行
select 'Front'
我一直不喜欢 Capybara 的 'locator' 概念有多么严格(即必须有一个 name/id/label),但是如果你深入研究源代码,那些有用的方法比如 select
、click_on
和 fill_in
只是 find
的包装器和 Element 的一些本地方法,它采用任意 CSS,几乎适用于所有情况.在这种情况下,您可以使用:
find('[name="vehicle_attrs[position_count]"]').find('option', text: 'Front').select_option
由于下拉菜单通常有多个相似的选项,其中一个是另一个的子字符串,您可以考虑使用精确的字符串匹配,例如
find('[name="vehicle_attrs[position_count]"]').find('option', text: /\AFront\z/).select_option
我在使用来自这个 select 元素的 selecting 时遇到问题。
<select name="vehicle_attrs[position_count]" class="mb1"><option>Position / Quantity</option><option>Front</option><option>Rear</option></select>
我试过了
select('Front', :from=>'mb1')
select('Front', :from=>'vehicle_attrs[position_count]')
select('Front', :from=>'vehicle_attrs[1]')
全部导致找不到selection box错误
从 select
的文档 - https://www.rubydoc.info/github/teamcapybara/capybara/Capybara/Node/Actions#select-instance_method - 我们可以看到 from
选项采用 "The id, Capybara.test_id atrtribute, name or label of the select box"。
'mb1' 或 'vehicle_attrs[1]' 都不是这些,因此预计它们会失败。
'vehicle_attrs[position_count]' 是名称,所以假设该框在页面上实际上是可见的(没有替换为 JS 驱动的 select 小部件等),那应该可以工作。如果没有,请编辑您的问题并添加您在尝试使用它时收到的完整错误消息。当然,如果页面上只有一个 select 框带有 'Front' 选项,那么您根本不需要指定 from
选项,只需执行
select 'Front'
我一直不喜欢 Capybara 的 'locator' 概念有多么严格(即必须有一个 name/id/label),但是如果你深入研究源代码,那些有用的方法比如 select
、click_on
和 fill_in
只是 find
的包装器和 Element 的一些本地方法,它采用任意 CSS,几乎适用于所有情况.在这种情况下,您可以使用:
find('[name="vehicle_attrs[position_count]"]').find('option', text: 'Front').select_option
由于下拉菜单通常有多个相似的选项,其中一个是另一个的子字符串,您可以考虑使用精确的字符串匹配,例如
find('[name="vehicle_attrs[position_count]"]').find('option', text: /\AFront\z/).select_option