laravel - 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');
在查看原始数据库时,我可以看到该列存在并且有数据。
解决方案
推荐阅读
- html - Bootstrap 4 HTML 工具提示
- c - 我如何知道c编程二维字符串数组中的ascii码?
- python - 在 pandas 中有效地搜索字符串和标签搜索词
- model - Lasso CV 或 ridge CV 中的 ALPHA 是否有一个最佳值,我们可以在大多数情况下提出?
- android - ContentResolver 插入方法发生 java.lang.IllegalArgumentException
- python-3.x - 检测周日到周六日期窗口并修改 Dataframe 的代码
- c# - 使用 IList IEnumerable 存储库实现分页列表
- angular - Bootstrap 没有安装在 Angular 中
- api - YouTube 频道喜欢和不喜欢
- java - 具有相同类路径但行为不同的两个 URLClassLoader