我不明白为什么该数据库测试失败。我知道我没有对created_at和updated_at列进行断言,但是三列(id,user_id,thing_id)应该足够,并且我敢肯定,我之前只对部分列进行了测试,它起作用了!
我想念什么?
Failed asserting that a row in the table [thing_history] matches the attributes [
{
"id": 1,
"user_id": 1,
"thing_id": 1
},
{
"id": 2,
"user_id": 1,
"thing_id": 2
},
{
"id": 3,
"user_id": 1,
"thing_id": 3
}
].
Found: [
{
"id": "1",
"user_id": "1",
"thing_id": "1",
"created_at": "2019-02-01 21:18:17",
"updated_at": "2019-02-01 21:18:17"
},
{
"id": "2",
"user_id": "1",
"thing_id": "2",
"created_at": "2019-02-01 21:18:17",
"updated_at": "2019-02-01 21:18:17"
},
{
"id": "3",
"user_id": "1",
"thing_id": "3",
"created_at": "2019-02-01 21:18:17",
"updated_at": "2019-02-01 21:18:17"
}
]
This is the test code
/** @test */
public function retrieving_feed_creates_history()
{
$user = factory('App\User')->create();
$this->actingAs($user);
factory('App\Thing', 3)->create();
$response = $this->json('GET', '/api/thing/feed/all');
$this->assertDatabaseHas('feed_histories', [
[
'id' => 1,
'thing_id' => 1,
'user_id' => $user->id,
],
[
'id' => 2,
'thing_id' => 2,
'user_id' => $user->id,
],
[
'id' => 3,
'thing_id' => 3,
'user_id' => $user->id,
]
]);
}
这是迁移代码:
public function up()
{
Schema::create('feed_histories', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('thing_id');
$table->timestamps();
});
}
答案 0 :(得分:1)
是的,多个记录的映射失败,因为assertDatabaseHas函数当前仅通过在where子句中映射单行来处理单行...
要获得更好的见解,可以看一下assertDatabaseHas的基本功能
public function matches($table): bool
{
return $this->database->table($table)->where($this->data)->count() > 0;
}
此处,$ this->数据引用assertDatabase的第二个参数。 因此,它清除了我们为什么不能传递数组的疑问。
答案 1 :(得分:0)
似乎我误解了一些东西。要检查几行,我必须将测试分为每行单独的断言。
这很好:
$this->assertDatabaseHas('feed_histories', [
'thing_id' => $thingA->id,
'user_id' => $user->id,
]);
$this->assertDatabaseHas('feed_histories', [
'thing_id' => $thingB->id,
'user_id' => $user->id,
]);