2011-04-19 84 views
12

考慮下面的下拉列表來得到它的名字/標籤:下拉與選擇的項目,如何使用水豚

<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 

但我怎樣才能得到當前選擇的名稱/標籤(平移在這裏)?下面的代碼做工作:

find_field("#my-dropdown").label 

謝謝:)

回答

18

您可以使用CSS3選擇器查找所選擇的項目,

http://net.tutsplus.com/tutorials/html-css-techniques/the-30-css-selectors-you-must-memorize/

,並稱之爲 '文本' 的方法在獲取文本的元素上。

http://rubydoc.info/github/jnicklas/capybara/master/Capybara/Node/Element:text

嘗試:

find_field('#my-dropdown option[selected]').text 
+1

只有在某個選項元素上明確設置了「selected」屬性時,此功能纔有效。一個簡單的方法是找到下拉列表的'selectedIndex',然後使用':nth-​​child'僞選擇器來抓取當前選擇的選項(這將是'selectedIndex + 1') – 2013-08-01 20:15:17

+0

我沒有調試它,但'find_field'沒有與水豚2.3.0。 'find('#my-dropdown option [selected]')。text' worked properly – jmgarnier 2014-11-13 20:14:25

3

如果您更喜歡使用標籤,你可以鏈的發現:

find_field('My Dropdown').find('option[selected]').text 

的find_field的上下文中找到搜索。

+1

這隻適用於默認選項,而不是輸入改變時。 – 2012-04-20 10:32:30

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 
0

基於由M.斯科特·福特的回答,我能夠想出下面的函數(其中字段是一個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 
0

你可以試試這個! find('#MyFieldId option[selected]').text

相關問題