首页 > 解决方案 > Laravel forgen 密钥未通过测试

问题描述

我正在通过 Laravel 中的 TDD 工作。我有一个Location看起来像这样的工厂:

位置工厂

$factory->define(Location::class, function (Faker $faker) {
return [
    'owner_id' => function () {
        return factory(User::class)->create()->id;
    },
    'name' => $faker->company,
    ...
    ];
});

我的测试如下所示:

位置测试

// Allow Laravel to handle the exception.
$this->withExceptionHandling();

// Create an authenticated user instance.
$user = factory(User::class)->create();

// Create the location instances via a factory.
$location = factory(Location::class)->create();

// An authenticated user can send a POST request to /locations to create a new location.
$response = $this->actingAs($user)->post('/locations', $location->toArray());

// Assert the system should persist the data to the database.
$this->assertDatabaseHas('locations', [
    'id' => $location->id,
    'owner_id' => $location->owner_id,
    'name' => $location->name,
    'description' => $location->description,
    'address' => $location->address,
    'address2' => $location->address2,
    'city' => $location->city,
    'state' => $location->state,
    'zip' => $location->zip,
    'created_at' => $location->created_at,
    'updated_at' => $location->updated_at,
    'deleted_at' => null,
]);

// Assert the response.
$response->assertSessionHasNoErrors();
$response->assertStatus(200);

我得到的错误很明显:

[
    "The owner id field is required."
]
Failed asserting that true is false.

但是,我知道我owner_id在测试中得到了一个:

dd($location);

 #original: array:12 [
     "owner_id" => 665
     ...

这是我的控制器的片段 - 我如何保存位置。

位置控制器

$attributes = $request->validate([
    'owner_id' => 'required',
    'name' => 'required',
    ...
]);

$location = Location::create($attributes);
$location->owner_id = auth()->id();
$location->save();

我的位置模型如下所示:

protected $fillable = [
    'name', 'description', 'address', 'address2', 'city', 'state', 'zip',
];

/**
 * The attributes that aren't mass assignable.
 *
 * @var array
 */
protected $guarded = [
    'owner_id',
];

使用望远镜我可以看到它owner_id不在阵列中。我不确定我做错了什么。

感谢您的任何建议!

编辑

检查我的迁移以确保该字段存在:

$table->unsignedInteger('owner_id');

在查看原始数据库时,我可以看到该列存在并且有数据。

标签: laraveltddlaravel-5.8

解决方案


推荐阅读