用貂皮擴充套件 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()]"