jeffochoa/factory-stories

在 Laravel 5.* 中创建模型工厂故事

1.1 2017-09-06 19:33 UTC

This package is auto-updated.

Last update: 2024-09-11 14:35:48 UTC


README

此包允许你在独立的类中创建复杂的模型工厂,以便在测试类之间重用。

灵感来源于 Model Factories podcasttwentypercent.fm

安装

$ composer require jeffochoa/factory-stories

如果你正在使用 Laravel 5.4 或更低版本,请将服务提供者添加到 app.php 文件中

FactoryStories\Providers\StoryFactoryServiceProvider::class

Laravel 5.5+ 将会自动发现提供者。

问题

假设你需要对具有某些条件的文章进行测试,例如

// Active articles, from Active Users, with tags attached

你可能会创建如下内容

$user = factory(User::class)->states('active');
$tags = factory(Taxonomy::class, 3)->states('tag')->create();
$article = factory(Article::class)->create([
    user_id => $user->id
]);
$article->tags()->attach($tags->pluck('id')->toArray());

... 或者类似的东西。

当然,你可以总是将其提取到自己的辅助类方法中,但有时你可能希望每种类型的“故事”都在自己的类中,特别是当你需要添加一些额外的方法来生成更复杂的数据时。

创建新的工厂故事

安装此包后,你将可以访问一个新的 artisan 命令

$ php artisan make:factory-story SomeClassName

运行此命令后,你应该会在 "database/" 目录下看到新文件

<?php

use App\Models\User;
use FactoryStories\FactoryStory;

class TestStory extends FactoryStory
{
    public function build($params = [])
    {
        // here you can add your complex model factories with their relationships
        return factory(User::class)->create();
    }

    // and You can add custom methods if You need to
}

使用工厂故事

考虑这个 UserTestClass.php

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ManageUsersTest extends TestCase
{
    use DatabaseMigrations;

    /** @test **/
    public function your_test_method()
    {
         //
    }

}

你只需要创建 Story 类的一个新实例,并在其上调用 create() 方法

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ManageUsersTest extends TestCase
{
    use DatabaseMigrations;

    /** @test **/
    public function your_test_method()
    {
         $article = (new ActiveUserArticleWithTags)
            ->times(5)->create();
    }
}

这将返回一个包含 5 个对象的集合,这些对象是你返回的自定义故事类中 build() 方法的对象。

Laravel 5.4 包含“实时外观”,这允许你通过在文件顶部添加 use Facades\{YourClassName} 将 Story 类用作外观。

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Facades\ActiveUserArticleWithTags;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ManageUsersTest extends TestCase
{
    use DatabaseMigrations;

    /** @test **/
    public function your_test_method()
    {
         $article = ActiveUserArticleWithTags::times(5)->create();
    }
}