Home  >  Article  >  Backend Development  >  Let’s start with Laravel, BDD, and you

Let’s start with Laravel, BDD, and you

WBOY
WBOYOriginal
2023-09-01 18:09:121419browse

让我们从 Laravel、BDD 和你开始

Welcome to a series about developing Laravel applications using a behavior-driven development (BDD) approach. Full-stack BDD can seem complex and intimidating. There are as many ways to achieve this as there are developers.

In this series, I'll walk you through designing a Laravel application from scratch using Behat and PhpSpec.

There are many resources on BDD in general, but Laravel specific material is hard to find. So, in this series, we will focus more on Laravel related aspects rather than the general stuff that you can read in many other places.

Describe behavior

When describing behaviors (also known as writing stories and specifications), we will use an outside-in approach. This means that every time we build a new feature, we start by writing an entire user story. This is usually from a customer or stakeholder perspective.

What do we expect to happen when we do this? 块引用>

Unless we refactor existing code, we are not allowed to write any code unless we hit a failed red step.

Sometimes, it's necessary to iteratively tackle a small part of the story or feature (I use the two words interchangeably) that we're working on. This usually means writing specifications using PhpSpec. Sometimes it takes multiple iterations at the integration or unit level before the entire story is passed (at the acceptance level). This all sounds complicated, but it's not. I'm a big believer in learning by doing, so I think it will all make more sense once we start writing some actual code.

We will be writing stories and specs on four different levels:

1. Acceptance

Most of the time, our feature suite will act as our acceptance layer. The way we describe features in a feature suite will be very similar to the way we write acceptance stories (using the Automated Browser Framework), so there will be a lot of duplication.

As long as the stories describe the behavior from the customer's perspective, they qualify as acceptance stories. We will use Symfony DomCrawler to test the output of the application. Later in this series, we may find that we need to test with an actual browser that can also run JavaScript. Testing via the browser adds some new issues, as we need to ensure the hourly test environment is loaded while the suite is running.

2. Functionality

In our feature suite we will have access to Laravel applications, which is very convenient. First, it allows easy differentiation of environments. Second, not going through the browser makes our test suite faster. Whenever we want to implement a new feature, we use Behat to write a story in our feature suite.

3. Integration

Our integration suite will test the behavior of core parts of the application that do not necessarily require access to Laravel. Integrated suites are often a mixture of Behat stories and PhpSpec specifications.

4.Unit

Our unit tests will be written in PhpSpec and will test independent small units at the core of the application. Our entities, value objects, etc. will all have specifications.

Case

In this series, starting with the next article, we will build a system for tracking time. We will first describe the external behavior by writing a Behat trait. The internal behavior of our application will be described using PhpSpec.

Together these two tools will help us feel satisfied with the quality of the application we are building. We will primarily write features and specifications on three levels:

  1. Feature
  2. integrated
  3. unit

In our feature suite, we will scrape the HTTP response of the application in headless mode, which means we will not go through the browser. This will make it easier to interact with Laravel and allow our suite of features to also act as our acceptance layer.

Later, if we end up with a more complex UI and maybe need to test some JavaScript as well, we might add a dedicated acceptance suite. The series is still a work in progress, so feel free to drop your suggestions in the comments section.

Our settings

Please note that in this tutorial I am assuming you have a clean installation and running of Laravel (4.2). It's best if you also use Laravel Homestead, which is what I used while writing this code.

Before starting any real work, let's make sure Behat and PhpSpec are up and running. First off, whenever I start a new Laravel project, I like to do a little cleanup and remove stuff I don't need:

git rm -r app/tests/ phpunit.xml CONTRIBUTING.md

If you delete these files, be sure to update your composer.json file accordingly:

"autoload": {
    "classmap": [
        "app/commands",
        "app/controllers",
        "app/models",
        "app/database/migrations",
        "app/database/seeds"
    ]
},

certainly:

$ composer dump-autoload

Now we are ready to introduce the BDD tools we need. Just add the require-dev section to your composer.json:

"require": {
    "laravel/framework": "4.2.*"
},
"require-dev": {
    "behat/behat": "~3.0",
    "phpspec/phpspec": "~2.0",
    "phpunit/phpunit": "~4.1"
},

“我们为什么要引入 PHPUnit?”你可能在想?在本系列中,我们不会编写优秀的 PHPUnit 测试用例,但断言与 Behat 一起是一个方便的工具。我们将在本文后面编写第一个功能时看到这一点。

请记住在修改 composer.json 后更新依赖项:

$ composer update --dev

我们即将完成安装和设置。 PhpSpec 开箱即用:

$ vendor/bin/phpspec run

0 specs
0 examples 
0ms

但是 Behat 需要使用 --init 选项快速运行才能设置所有内容:

$ vendor/bin/behat --init

+d features - place your *.feature files here
+d features/bootstrap - place your context classes here
+f features/bootstrap/FeatureContext.php - place your definitions, transformations and hooks here

$ vendor/bin/behat

No scenarios
No steps
0m0.14s (12.18Mb)

第一个命令创建了一个闪亮的新 FeatureContext 类,我们可以在其中编写功能所需的步骤定义:

<?php

use Behat\Behat\Context\SnippetAcceptingContext;
use Behat\Gherkin\Node\PyStringNode;
use Behat\Gherkin\Node\TableNode;

/**
 * Behat context class.
 */
class FeatureContext implements SnippetAcceptingContext
{
    /**
     * Initializes context.
     *
     * Every scenario gets its own context object.
     * You can also pass arbitrary arguments to the context constructor through behat.yml.
     */
    public function __construct()
    {
    }
}

编写我们的第一个功能

我们的第一个功能非常简单:我们只需确保新的 Laravel 安装以“您已到达”来迎接我们。在主页上。我还添加了一个相当愚蠢的 Given 步骤,假设我登录了 ,这仅用于显示在我们的功能中与 Laravel 交互是多么容易。

从技术上讲,我将这种类型的功能归类为功能测试,因为它与框架交互,但它也可以作为验收测试,因为我们不会看到通过浏览器测试运行类似测试有任何不同的结果工具。现在我们将坚持使用我们的功能测试套件。

继续创建一个 welcome.feature 文件并将其放入 features/functions:

# features/functional/welcome.feature

Feature: Welcoming developer
    As a Laravel developer
    In order to proberly begin a new project
    I need to be greeted upon arrival

    Scenario: Greeting developer on homepage
        Given I am logged in
        When I visit "/"
        Then I should see "You have arrived."

通过将功能特性放在 featured 目录中,我们以后可以更轻松地管理我们的套件。我们不希望不需要 Laravel 的集成类型功能必须等待缓慢的功能套件。

我喜欢让事情保持美观和干净,所以我相信我们应该为我们的功能套件提供一个专用的功能上下文,以便我们可以访问 Laravel。您可以继续复制现有的 FeatureContext 文件并将类名称更改为 LaravelFeatureContext。为此,我们还需要一个 behat.yml 配置文件。

在项目的根目录中创建一个并添加以下内容:

default:
    suites:
        functional:
            paths: [ %paths.base%/features/functional ]
            contexts: [ LaravelFeatureContext ]

我认为这里的 YAML 是非常不言自明的。我们的功能套件将在 functioning 目录中查找功能,并通过 LaravelFeatureContext 运行它们。

如果我们此时尝试运行 Behat,它会告诉我们实现必要的步骤定义。我们可以使用以下命令让 Behat 将空脚手架方法添加到 LaravelFeatureContext 中:

$ vendor/bin/behat --dry-run --append-snippets
$ vendor/bin/behat

Feature: Welcoming developer
    As a Laravel developer
    In order to proberly begin a new project
    I need to be greeted upon arival

  Scenario: Greeting developer on homepage # features/functional/welcome.feature:6
    Given I am logged in                   # LaravelFeatureContext::iAmLoggedIn()
      TODO: write pending definition
    When I visit "/"                       # LaravelFeatureContext::iVisit()
    Then I should see "You have arrived."  # LaravelFeatureContext::iShouldSee()

1 scenario (1 pending)
3 steps (1 pending, 2 skipped)
0m0.28s (12.53Mb)

现在,正如您从输出中看到的那样,我们已准备好开始实施第一个步骤:鉴于我已登录

Laravel 附带的 PHPUnit 测试用例允许我们执行诸如 $this->be($user) 之类的操作,它会登录给定用户。最终,我们希望能够像使用 PHPUnit 一样与 Laravel 交互,所以让我们继续编写“我们希望拥有”的步骤定义代码:

/**
 * @Given I am logged in
 */
public function iAmLoggedIn()
{
    $user = new User;

    $this->be($user);
}

这当然行不通,因为 Behat 不知道 Laravel 的具体内容,但我很快就会向您展示让 Behat 和 Laravel 很好地协同工作是多么容易。

如果您查看 Laravel 源代码并找到 Illuminate\Foundation\Testing\TestCase 类(默认测试用例扩展自该类),您会发现从 Laravel 4.2 开始,一切都已更改转移到一个特质。 ApplicationTrait 现在负责启动 Application 实例、设置 HTTP 客户端并为我们提供一些辅助方法,例如 be()

这非常酷,主要是因为这意味着我们可以将其拉入我们的 Behat 上下文中,几乎不需要任何设置。我们还可以访问 AssertionsTrait,但这仍然与 PHPUnit 相关。

当我们引入特征时,我们需要做两件事。我们需要一个 setUp() 方法,如 Illuminate\Foundation\Testing\TestCase 类中的方法,并且需要一个 createApplication() 方法,如默认 Laravel 测试用例中的方法。其实我们直接复制这两个方法就可以了。

只有一件事需要注意:在 PHPUnit 中,方法 setUp() 会在每次测试之前自动调用。为了在 Behat 中实现相同的效果,我们可以使用 @BeforeScenario 注释。

将以下内容添加到您的 LaravelFeatureContext

use Illuminate\Foundation\Testing\ApplicationTrait;

/**
 * Behat context class.
 */
class LaravelFeatureContext implements SnippetAcceptingContext
{
    /**
     * Responsible for providing a Laravel app instance.
     */
    use ApplicationTrait;

    /**
     * Initializes context.
     *
     * Every scenario gets its own context object.
     * You can also pass arbitrary arguments to the context constructor through behat.yml.
     */
    public function __construct()
    {
    }

    /**
     * @BeforeScenario
     */
    public function setUp()
    {
        if ( ! $this->app)
        {
            $this->refreshApplication();
        }
    }

    /**
     * Creates the application.
     *
     * @return \Symfony\Component\HttpKernel\HttpKernelInterface
     */
    public function createApplication()
    {
        $unitTesting = true;

        $testEnvironment = 'testing';

        return require __DIR__.'/../../bootstrap/start.php';
    }

非常简单,看看我们运行 Behat 时得到的结果:

$ vendor/bin/behat

Feature: Welcoming developer
    As a Laravel developer
    In order to proberly begin a new project
    I need to be greeted upon arival

  Scenario: Greeting developer on homepage # features/functional/welcome.feature:6
    Given I am logged in                   # LaravelFeatureContext::iAmLoggedIn()
    When I visit "/"                       # LaravelFeatureContext::iVisit()
      TODO: write pending definition
    Then I should see "You have arrived."  # LaravelFeatureContext::iShouldSee()

1 scenario (1 pending)
3 steps (1 passed, 1 pending, 1 skipped)
0m0.73s (17.92Mb)

绿色的第一步,这意味着我们的设置正在运行!

接下来,我们可以实现 当我访问 步骤。这个非常简单,我们可以简单地使用 ApplicationTrait 提供的 call() 方法。一行代码即可实现:

/**
 * @When I visit :uri
 */
public function iVisit($uri)
{
    $this->call('GET', $uri);
}

最后一步,然后我应该看到,需要更多一点,我们需要引入两个依赖项。我们需要 PHPUnit 来进行断言,并且需要 Symfony DomCrawler 来搜索“您已到达”。文本。

我们可以这样实现:

use PHPUnit_Framework_Assert as PHPUnit;
use Symfony\Component\DomCrawler\Crawler;

...

/**
 * @Then I should see :text
 */
public function iShouldSee($text)
{
    $crawler = new Crawler($this->client->getResponse()->getContent());

    PHPUnit::assertCount(1, $crawler->filterXpath("//text()[. = '{$text}']"));
}

这与您使用 PHPUnit 时编写的代码几乎相同。 filterXpath() 部分有点令人困惑,我们现在不用担心它,因为它有点超出了本文的范围。请相信我,它有效。

最后一次跑步是个好消息:

$ vendor/bin/behat
Feature: Welcoming developer
    As a Laravel developer
    In order to proberly begin a new project
    I need to be greeted upon arival

  Scenario: Greeting developer on homepage # features/functional/welcome.feature:6
    Given I am logged in                   # LaravelFeatureContext::iAmLoggedIn()
    When I visit "/"                       # LaravelFeatureContext::iVisit()
    Then I should see "You have arrived."  # LaravelFeatureContext::iShouldSee()

1 scenario (1 passed)
3 steps (3 passed)
0m0.82s (19.46Mb)

该功能正在按预期工作,并且开发人员在抵达时受到欢迎。

结论

完整的 LaravelFeatureContext 现在应该与此类似:

call('GET', $uri);
    }

    /**
     * @Then I should see :text
     */
    public function iShouldSee($text)
    {
        $crawler = new Crawler($this->client->getResponse()->getContent());

        PHPUnit::assertCount(1, $crawler->filterXpath("//text()[. = '{$text}']"));
    }
}

随着我们继续使用 BDD 开发新的 Laravel 应用程序,我们现在已经有了一个非常好的基础。我希望我已经向您证明了让 Laravel 和 Behat 很好地协同工作是多么容易。

我们在第一篇文章中讨论了许多不同的主题。不用担心,随着本系列的继续,我们将更深入地研究一切。如果您有任何问题或建议,请留言。

The above is the detailed content of Let’s start with Laravel, BDD, and you. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Redirect tutorial in PHPNext article:Redirect tutorial in PHP