Hardcoding 1 assumes your database is empty at the start of the test. Maybe you forgot to use DatabaseMigrations, DatabaseTransactions; in your Test class?
Super weird test failure with assertDatabaseHas
Hello,
I've got a super weird thing going on for 3 days now. And I can't get it to work.
I've got 2 tables:
Company
Products
And a pivot table company_products.
So in my webapp everything is working. However in my test it keeps failing.
This is the test:
/** @test */
public function when_a_product_is_destroyed_linked_companies_will_go_away()
{
$product = create(Product::class);
create(Company::class)->syncProducts([$product->toArray()]);
$this->actingAs($this->user)->deleteJson('/producten/'.$product->id);
$this->assertDatabaseMissing('company_products', [
'product_id' => '1',
'company_id' => '1',
]);
Pretty simple I create a product and sync it with a company. Then I destroy the product and check if the relations are gone in the pivot table. This is the exact failure I get:
There was 1 failure:
1) Tests\Feature\Product\DeleteProductTest::when_a_product_is_destroyed_linked_companies_will_go_away
Failed asserting that a row in the table [company_products] does not match the attributes {
"product_id": "1",
"company_id": "1"
}.
Found: [
{
"product_id": "1",
"company_id": "1"
}
].
So I've checked it a 1000 times manually in my webapp and the relation goes away in my pivot table (I use foreign keys). But the test keeps failing.
The controller method destroy looks like this:
/**
* Destroy a product.
*
* @param Product $product
* @return \Illuminate\Http\JsonResponse
*/
public function destroy(Product $product)
{
$this->productRepo->delete($product->id);
return response()->json(['status' => 'Verwijderd']);
}
When I dd in my test like this:
/**
* Destroy a product.
*
* @param Product $product
* @return \Illuminate\Http\JsonResponse
*/
public function destroy(Product $product)
{
$this->productRepo->delete($product->id);
DD(DB::table('company_products)
->select(DB::raw('*'))
->get());
return response()->json(['status' => 'Verwijderd']);
}
I receive this:
There was 1 failure:
1) Tests\Feature\Product\DeleteProductTest::when_a_product_is_destroyed_linked_companies_will_go_away
Failed asserting that a row in the table [company_products] does not match the attributes {
"product_id": "1",
"company_id": "1"
}.
Found: [
{
"product_id": "1",
"company_id": "1"
}
].
When I do the exact same thing but then in my webapp I receive:
Collection {#531
#items: []
}
What the hack could be going on here?
Are you depending on the database to cascade delete? Are you using SQLite for testing? Does SQLite support cascading deletes?
Please or to participate in this conversation.