Laravel枢轴表测试

时间:2017-07-16 12:41:27

标签: php laravel pivot

我有一个测试,我检查是否正在删除数据透视表中的记录。测试看起来像这样:

/** @test */
public function when_a_relation_is_destroyed_linked_products_will_go_away()
{
    $products = create(Product::class, [], 3)->toArray();
    $relation = create(Relation::class)->syncProducts($products);

    $this->actingAs($this->user)->deleteJson('/relaties/'.$relation->id);

    $this->assertDatabaseMissing('product_has_relations', [
        "product_id" => "1", "relation_id" => "1",
        "product_id" => "2", "relation_id" => "1",
        "product_id" => "3", "relation_id" => "1"
    ]);
}

当我在我的实际应用程序中测试它时,数据透视表中的记录被正确删除。但我的测试仍然失败:

Failed asserting that a row in the table [product_has_relations] does not match the attributes {
    "product_id": "3",
    "relation_id": "1"
}.

Found: [
    {
        "product_id": "1",
        "relation_id": "1"
    },
    {
        "product_id": "2",
        "relation_id": "1"
    },
    {
        "product_id": "3",
        "relation_id": "1"
    }
].

这不起作用:

$this->assertDatabaseMissing('product_has_relations', [
    ["product_id" => "1", "relation_id" => "1"],
    ["product_id" => "2", "relation_id" => "1"],
    ["product_id" => "3", "relation_id" => "1"]
]);

知道这里有什么问题吗?

1 个答案:

答案 0 :(得分:0)

您的问题在$this->actingAs($this->user)->deleteJson('/relaties/'.$relation->id);

记录不会被删除,因此测试失败。