使用工厂测试 Laravel post 请求

Dam*_*mon 2 tdd laravel-5

我正在为我的 Laravel 应用程序编写一些功能测试。我是 TDD 新手,所以这对某些人来说可能是显而易见的。

LocationsFactory.php

use Faker\Generator as Faker;

$factory->define(App\Location::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
    ];
});
Run Code Online (Sandbox Code Playgroud)

位置测试.php

public function a_user_can_create_a_location(): void
{
    $this->withExceptionHandling();

    $user = factory(User::class)->make();
    $location = factory(Location::class)->make();


    $response = $this->actingAs($user)->post('/locations', $location);  // $location needs to be an array

    $response->assertStatus(200);
    $this->assertDatabaseHas('locations', ['name' => $location->name]);
}
Run Code Online (Sandbox Code Playgroud)

类型错误:传递给 Illuminate\Foundation\Testing\TestCase::post() 的参数 2 必须是数组类型,给定对象

我知道错误告诉我$location需要是一个数组并且它是一个对象。然而,由于我使用的是工厂,它作为一个对象出现。有没有更好的方法在我的测试中使用工厂?

这似乎也有点不对劲:

$this->assertDatabaseHas('locations', ['name' => $location->name]);
Run Code Online (Sandbox Code Playgroud)

由于我使用的是 faker,所以我不知道name会发生什么。所以我只是检查生成的内容是否理想?

感谢您的任何建议!

编辑

做这样的事情效果很好(也许这就是解决方案)......

...
$user = factory(User::class)->make();
$location = factory(Location::class)->make();

$response = $this->actingAs($user)->post('/locations', [
    'name' => $location->name
]);

$response->assertStatus(200);
$this->assertDatabaseHas('locations', ['name' => $location->name]);
Run Code Online (Sandbox Code Playgroud)

然而,假设我的location有 30 个属性。看起来它很快就会变得丑陋。

Ras*_*gor 5

拉拉维尔 5

用于toArray()对象到数组的转换:请参阅以下示例

    $user = factory(User::class)->make();
    $location = factory(Location::class)->make();

    $response = $this->actingAs($user)->post('/locations', $location->toArray());

    $response->assertStatus(200);
    $this->assertDatabaseHas('locations', ['name' => $location->name]);
Run Code Online (Sandbox Code Playgroud)