Как проверить выбранный вариант из выпадающего списка с помощью Behat/Mink

На странице есть несколько фильтров, и я хотел бы проверить значения фильтров по умолчанию. Я не могу заставить работать селекторы. Может кто-нибудь помочь.

Вот фрагмент кода:

<div class="filter-widget">
<form name="" method="post" action="">
<div class="pure-g-r">
    <div class="pure-u-1-4">
    <div><label for="day" class="required">Day</label><select id="day" name="day">    <option value="all">all</option><option value="Sunday">Sunday</option><option value="Monday">Monday</option><option value="Tuesday">Tuesday</option><option value="Wednesday">Wednesday</option><option value="Thursday" selected="selected">Thursday</option><option value="Friday">Friday</option><option value="Saturday">Saturday</option></select></div>
</div>
<div class="pure-u-1-4">
    <div><label for="month" class="required">Month</label><select id="month" name="month"><option value="January">January</option><option value="February">February</option><option value="March">March</option><option value="April" selected="selected">April</option><option value="May">May</option><option value="June">June</option><option value="July">July</option><option value="August">August</option><option value="September">September</option><option value="October">October</option><option value="November">November</option><option value="December">December</option></select></div>
</div>
</div>

Как вы можете видеть выше, фильтры по умолчанию используют текущий день/месяц, и мне нужно проверить эти значения. Но используемый ниже селектор css не работает. Поддерживается ли он в Behat?

$page = $this->getSession()->getPage();
$defaultFilterDay = $page->find('css', '#day select option:selected')->getText();
$defaultFilterMonth = $page->find('css', '#month select option:selected')->getText();
$currentDay = new \DateTime('now')->format('l'); //This returns current Day
$currentMonth = new \DateTime('now')->format('F'); //This returns current Month

assertEquals(currentDay, $defaultFilterDay);
assertEquals(currentMonth, $defaultFilterMonth);

person vijay pujar    schedule 03.04.2014    source источник
comment
Это было довольно легко с помощью jQuery. Но мне сложно работать с селекторами CSS.   -  person vijay pujar    schedule 03.04.2014


Ответы (6)


У меня была та же проблема, я хотел определить значение выбранного параметра, используя значение параметра и селектор select css. Вот что я в итоге сделал:

/**
 * @Then /^the option "([^"]*)" from select "([^"]*)" is selected$/
 */
public function theOptionFromSelectIsSelected($optionValue, $select)
{
    $selectField = $this->getSession()->getPage()->find('css',$select);
    if (null === $selectField) {
        throw new \Exception(sprintf('The select "%s" was not found in the page %s', $select, $this->getSession()->getCurrentUrl()));
    }

    $optionField = $selectField->find('xpath', "//option[@selected='selected']");
    if (null === $optionField) {
        throw new \Exception(sprintf('No option is selected in the %s select in the page %s', $select, $this->getSession()->getCurrentUrl()));
    }

    if ($optionField->getValue() != $optionValue) {
        throw new \Exception(sprintf('The option "%s" was not selected in the page %s, %s was selected', $optionValue, $this->getSession()->getCurrentUrl(), $optionField->getValue()));
    }
}
person Dallas    schedule 19.10.2015
comment
Иногда выбранная опция не имеет атрибута со значением: selected=selected, если вы не хотите или не можете изменить это в тестируемом приложении, вы можете настроить реализацию определения шага следующим образом: $optionField = $selectField->find('xpath', "//option[@selected]"); - person Bernhard Zürn; 26.10.2018

Если вы не хотите добавлять пользовательские шаги в контекст своей функции, вы можете попробовать использовать селекторы CSS непосредственно в Gherkin:

Then the "select[name='day'] option[selected='selected']" element contains "Thursday"

And the "select[name='month'] option[selected='selected']" element contains "April"

person Dr. Curiosity    schedule 03.09.2015
comment
Я не хотел добавлять пользовательские шаги, но не мог заставить эту версию работать, пока немного не изменил ее: Then the "select[name='day'] option[selected='selected']" element should contain "Thursday" - person Selwyn Polit; 10.06.2020

Я сделал контекст с этим определением шага:

/**
 * Checks, that option from select with specified id|name|label|value is selected.
 *
 * @Then /^the "(?P<option>(?:[^"]|\\")*)" option from "(?P<select>(?:[^"]|\\")*)" (?:is|should be) selected/
 * @Then /^the option "(?P<option>(?:[^"]|\\")*)" from "(?P<select>(?:[^"]|\\")*)" (?:is|should be) selected$/
 * @Then /^"(?P<option>(?:[^"]|\\")*)" from "(?P<select>(?:[^"]|\\")*)" (?:is|should be) selected$/
 */
public function theOptionFromShouldBeSelected($option, $select)
{
    $selectField = $this->getSession()->getPage()->findField($select);
    if (null === $selectField) {
        throw new ElementNotFoundException($this->getSession(), 'select field', 'id|name|label|value', $select);
    }

    $optionField = $selectField->find('named', array(
        'option',
        $option,
    ));

    if (null === $optionField) {
        throw new ElementNotFoundException($this->getSession(), 'select option field', 'id|name|label|value', $option);
    }

    if (!$optionField->isSelected()) {
        throw new ExpectationException('Select option field with value|text "'.$option.'" is not selected in the select "'.$select.'"', $this->getSession()); 
    }
}

Таким образом, вы можете добавить следующий шаг в свои функции Behat:

Then the "Option 1" option from "Select options" should be selected

Вы можете увидеть полный код Context здесь: https://github.com/Aplyca/BehatContexts/blob/master/src/Aplyca/BehatContext/FormContext.php#L64

person Mauricio Sánchez    schedule 10.07.2015
comment
На самом деле это должно быть $optionField = $selectField-›find('named', array( 'option', \{$option}\, )); Без этого он не будет работать для опций с пробелами в - person Miro; 18.09.2015

Я использую следующий код для получения значения выбранного параметра

$elementByName = $this->getSession ()->getPage ()->find ( 'css', "#" . $name );

if (! $elementByName) {
    throw new FailureException ( 'select with name ' . $name . ' is not found' );
} else {
    $v = $elementByName->getValue ();
}
person Shadi Hariri    schedule 29.04.2014
comment
Спасибо за ваш ответ, но я нашел решение, опубликованное ниже - person vijay pujar; 08.09.2014

Если вы хотите утверждать, выберите такие значения:

And "4" from "Number of Columns" is selected
And "red" from "Background Color" is selected
And "plaid" from "Background Image" is selected

Затем используйте эту модифицированную/улучшенную версию с помощью ответа @Dallas.

  /**
   * @Then /^"([^"]*)" from "([^"]*)" is selected$/
   *
   * To assert a select value.
   * Shamelessly inspired by: https://stackoverflow.com/a/33223002/1038565
   */
  public function theOptionFromSelectIsSelected($optionValue, $select) {
    $selectField = $this->getSession()->getPage()->findField($select);

    if (NULL === $selectField) {
      throw new \Exception(sprintf('The select "%s" was not found in the page %s', $select, $this->getSession()->getCurrentUrl()));
    }

    $optionField = $selectField->find('xpath', "//option[@selected]");
    if (NULL === $optionField) {
      throw new \Exception(sprintf('No option is selected in the %s select in the page %s', $select, $this->getSession()->getCurrentUrl()));
  }

  if ($optionField->getValue() != $optionValue) {
    throw new \Exception(sprintf('The option "%s" was not selected in the page %s, %s was selected', $optionValue, $this->getSession()->getCurrentUrl(), $optionField->getValue()));
  }
}
person Beto Aveiga    schedule 16.10.2019

У меня работал следующий селектор:

$defaultFilterDay = $page->find("css", "#day option[selected='selected']")->getText();
    $defaultFilterMonth = $page->find("css", "#month option[selected='selected']")->getText();

    date_default_timezone_set('UTC');
    $currentTime = new \DateTime('now');
    $currentDay = $currentTime->format('l');
    $currentMonth = $currentTime->format('F');

    assertEquals($currentDay, $defaultFilterDay);
    assertEquals($currentMonth, $defaultFilterMonth);    
person vijay pujar    schedule 08.09.2014