2015-11-06 92 views
0

我正在嘗試編寫一個自定義方法,允許使用我們的自定義select2 country_search元素。這些元素都有點靠不住,但HTML的代碼片段看起來是這樣的:使用Capybara Select select2選擇範圍

<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> 

我寫了一個幫手應該選擇正確的span並在其上進行點擊,但我堅持選擇我想要的跨度。我試圖選擇具有類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元素,但我不能讓span兄弟姐妹不管我試試。

回答

1

如果我讀正確,你想要的跨度是div.controls的孩子,用下面的替換最後兩個認定應該這樣做

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

您可以在添加類跨度CSS選擇器如果需要,但在你的HTML它是唯一的跨越孩子,所以它沒有必要

+0

謝謝你,但我已經縮小了這個問題。這不是XPATH無效,問題是SPAN元素不在那裏。由於某些原因,當Capybara加載頁面時,即使使用Poltergeist,JavaScript也不會被執行。 –

+0

檢查您的瀏覽器控制檯中是否有任何錯誤。通常在開發模式下,JS文件被單獨加載,因此一個錯誤不會阻止其他人執行,但是在測試模式下,它們會被連接成一個JS文件,這意味着只有一個JS文件中的錯誤可以阻止在其他人的初始化代碼中執行。 –

+0

這是JS未加載,因爲測試是在不支持JS的標準Rack Runner下運行的。我已經重寫了整個測試設置,現在使用Poltergheist,並且一切正常。添加你的產品線的速度要快得多。 –