给出以下下拉列表:
<select id="my-dropdown" name="my-dropdown">
<option value="1">Peter</option>
<option value="2" selected>Pan</option>
</select>
我知道我可以使用以下代码获取当前选择的值(此处为2):
find_field("#my-dropdown").value
但是如何获得当前选择的名称/标签(Pan here)?以下代码执行不:
find_field("#my-dropdown").label
谢谢:)
答案 0 :(得分:18)
您可以使用css3选择器查找所选项目
http://net.tutsplus.com/tutorials/html-css-techniques/the-30-css-selectors-you-must-memorize/
并在元素上调用'text'方法以获取文本。
http://rubydoc.info/github/jnicklas/capybara/master/Capybara/Node/Element:text
尝试:
find_field('#my-dropdown option[selected]').text
答案 1 :(得分:4)
虽然其他答案很接近,但它们似乎与Capybara 1.1.2(我正在使用的版本)无关。在那个版本中,我发现以下方法有效,但仅仅因为我知道“应该”的值是什么。
#based on Capybara::Node::Actions#select
def find_select_option(select_finder, option_finder)
no_select_msg = "cannot select option, no select box with id, name, or label '#{select_finder}' found"
no_option_msg = "cannot select option, no option with text '#{option_finder}' in select box '#{select_finder}'"
select = find(:xpath, XPath::HTML.select(select_finder), :message => no_select_msg)
select.find(:xpath, XPath::HTML.option(option_finder), :message => no_option_msg)
end
find_select_option('Countries', 'United States').should be_selected
答案 2 :(得分:3)
如果您更喜欢使用标签,可以链接查找:
find_field('My Dropdown').find('option[selected]').text
find在find_field的上下文中搜索。
答案 3 :(得分:0)
根据M. Scott Ford的回答,我能够提出以下功能(其中field是id)
def field_should_have_value(field, value)
element = @session.find_field(field)
if !element
throw "field_should_have_value(#{field}, #{value}) - unable to fine field: #{field}"
end
# Question: is there any other way of doing: if element[:nodeName] == "select"
option = element.has_selector?("option") && element.find(:xpath, XPath::HTML.option(value))
if option
if element.value != value && option.text != value
throw "field_should_have_value(#{field}, #{value}) - value does not match. Expected: #{value}. Got element.value: #{element.value} || option.text: #{option.text}"
end
elsif element.value != value
throw "field_should_have_value(#{field}, #{value}) - value does not match. Expected: #{value}. Got element.option.text: #{option.text}"
end
end
答案 4 :(得分:0)
你可以试试这个!
find('#MyFieldId option[selected]').text