用貂皮扩展 Behat

Mink 为 Web 驱动程序(如 Goutte 和 Selenium)以及 MinkContext 提供了一个界面,当扩展时,它为我们的步骤提供了额外的 Web 语言。

要安装 Mink(和默认的 Goutte 驱动程序):

$ composer require --dev behat/mink-extension="^2.0"
$ composer require --dev behat/mink-goutte-driver="^1.0"

然后用 MinkContext 扩展你的上下文:

<?php
use Behat\MinkExtension\Context\MinkContext;

class FeatureContext extends MinkContext … {
    …
}

你可以使用以下命令查看 Behat 安装中可用的整个语法列表:

$ ./vendor/bin/behat -dl

Given /^(?:|I )am on "(?P<page>[^"]+)"$/
 When /^(?:|I )reload the page$/
 When /^(?:|I )move backward one page$/
 When /^(?:|I )move forward one page$/
 When /^(?:|I )press "(?P<button>(?:[^"]|\\")*)"$/
 When /^(?:|I )follow "(?P<link>(?:[^"]|\\")*)"$/
 When /^(?:|I )fill in "(?P<field>(?:[^"]|\\")*)" with "(?P<value>(?:[^"]|\\")*)"$/

然后,你需要配置 Mink 以指示要测试的网站所在的位置以及要使用的 Web 驱动程序(默认情况下为 Goutte):

# ./behat.yml
default:
    extensions:
        Behat\MinkExtension:
            base_url: "[your website URL]"
            sessions:
                default:
                    goutte: ~

以下是仅使用 Mink 提供的步骤的方案示例:

# ./features/Authentication.feature
Feature: Authentication
    As a security conscious developer I wish to ensure that only valid users can access our website.

    Scenario: Login in successfully to my website
        When I am on "/login"
        And I fill in "email" with "my@email.com"
        And I fill in "password" with "my_password"
        And I press "Login"
        Then I should see "Successfully logged in"

    Scenario: Attempt to login with invalid credentials
        When I am on "/login"
        And I fill in "email" with "my@email.com"
        And I fill in "password" with "not_my_password"
        And I press "Login"
        Then I should see "Login failed"

你现在可以通过 Behat 运行该功能来测试它:

./vendor/bin/behat features/Authentication.feature

你可以使用 MinkContext 创建自己的步骤以执行常见步骤(例如,登录是一种非常常见的操作):

Feature: Authentication
    As a security conscious developer I wish to ensure that only valid users can access our website.

    Scenario: Login in successfully to my website
        Given I login as "my@email.com" with password "my_password"
        Then I should see "Successfully logged in"

    Scenario: Attempt to login with invalid credentials
        Given I login as "my@email.com" with password "not_my_password"
        Then I should see "Login failed"

你需要使用 MinkContext 扩展你的上下文文件,以访问 Web 驱动程序和页面交互:

<?php
use Behat\MinkExtension\Context\MinkContext;

class FeatureContext extends MinkContext {
    /**
      * @Given I login as :username with password :password
      */
    public function iLoginAsWithPassword($username, $password) {
        $this->visit("/login");
        $this->fillField("email", $username);
        $this->fillField("password", $password);
        $this->pressButton("Login");
    }
}

Mink 还在大多数预先提供的调用中提供 CSS 选择器,允许你使用以下结构识别页面上的元素:

When I click on "div[id^='some-name']"
And I click on ".some-class:first"
And I click on "//html/body/table/thead/tr/th[first()]"