使用Behat如何验证select下拉选择框包含指定的选项集合
Behat校验select字段包含指定选项集合的实现方法
Behat原生MinkContext没有提供该校验能力,你可以通过自定义上下文方法实现,操作如下:
1. 新增自定义断言方法
在你的项目自定义Context文件中加入以下代码:
/** * 校验指定select字段包含给定的选项集合 * * @Then the select :select should contain the following options: */ public function assertSelectContainsOptions(string $select, \Behat\Gherkin\Node\TableNode $expectedOptions) { // 定位select字段元素 $selectField = $this->getSession()->getPage()->findField($select); if (null === $selectField) { throw new \Exception(sprintf('无法找到指定的select字段:%s', $select)); } // 获取select下所有option的展示文本 $actualOptions = array_map(function($option) { return trim($option->getText()); }, $selectField->findAll('css', 'option')); // 逐个校验预期选项是否存在 foreach ($expectedOptions->getColumn(0) as $expectedOption) { $trimmedExpected = trim($expectedOption); if (!in_array($trimmedExpected, $actualOptions)) { throw new \Exception(sprintf( 'select字段[%s]中缺少预期选项:%s,当前实际选项为:%s', $select, $trimmedExpected, implode(', ', $actualOptions) )); } } }
2. 场景中调用方式
在Gherkin用例中按以下格式编写校验步骤,传入目标select字段的id、name或关联label文本,以及预期选项列表即可:
Scenario: 校验注册页性别下拉选项完整 When I am on "/user/register" Then the select "gender" should contain the following options: | 男 | | 女 | | 保密 |
常用拓展调整
- 若需要校验option的value属性而非展示文本,将代码中
return trim($option->getText())改为return trim($option->getValue())即可 - 若需要校验选项完全匹配(既不能缺少预期选项,也不能存在多余选项),可在现有校验逻辑后补充以下代码:
$expectedOptionList = array_map('trim', $expectedOptions->getColumn(0)); sort($actualOptions); sort($expectedOptionList); if ($actualOptions !== $expectedOptionList) { throw new \Exception(sprintf( 'select字段选项和预期不匹配,预期选项:%s,实际选项:%s', implode(', ', $expectedOptionList), implode(', ', $actualOptions) )); }
内容的提问来源于stack exchange,提问作者Felix Eve
相关产品推荐
相关产品推荐

