Laravel forgen密钥未通过测试

时间:2019-03-18 19:48:59

标签: laravel tdd laravel-5.8

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

LocationFactory

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

我的测试如下:

LocationTest

// 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
     ...

这是我的控制器的摘要-我如何保存位置。

LocationController

$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',
];

使用telescope可以看到owner_id不在数组中。我不确定自己在做什么错。

谢谢您的任何建议!

修改

检查我的迁移,以确保该字段在那里:

$table->unsignedInteger('owner_id');

在正确查看原始数据库的同时,我可以看到该列存在并包含数据。

0 个答案:

没有答案