Подтвердить что ты не робот

Выпадающий список с выбранным элементом, как получить его имя/ярлык с помощью capybara

Учитывая следующее раскрывающееся меню:

<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 здесь) текущего выбора? Следующий код выполняет не:

find_field("#my-dropdown").label

Спасибо:)

4b9b3361

Ответ 2

В то время как другие ответы приблизились, они, похоже, не работали с 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

Ответ 3

Если вы предпочитаете использовать ярлыки, вы можете связать поиск:

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

Поиск ищет в контексте поля find_.

Ответ 4

Основываясь на ответе М. Скотта Форда, я смог придумать следующую функцию (где поле - 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

Ответ 5

Вы можете попробовать это! find('#MyFieldId option[selected]').text