I'm using Laravel 5.4 and PHPUnit 6.5.5. I keep getting the following error when using Laravel's assertDatabaseHas() method in my tests.
Error: Call to undefined method Illuminate\Http\Response::assertDatabaseHas()
This is my code fragment using assertDatabaseHas():
$response = $this->withSession(['user_id' => $this->user_id])
->json('post',
route('some_route'),
$request //an array
);
$request['myuser_id'] = $this->user_id;
$response->assertStatus($expected['code'])
->assertDatabaseHas('profiles',$request);
I also tried to use $this->assertDatabaseHas(), but a new error appeared:
TypeError: Argument 2 passed to PHPUnit\Framework\Assert::assertThat() must be an instance of PHPUnit\Framework\Constraint\Constraint, instance of Illuminate\Foundation\Testing\Constraints\HasInDatabase given, called in /project_path/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithDatabase.php on line 22
I searched for a while for the problem's solution and found this question , but downgrading PHPUnit version to 5.* didn't work for me.
assertDatabaseHas() always worked, you were just using it incorrectly and a change in Laravel versions would not have fixed your problem.
You're dealing with two separate entities here – an HTTP response and a database entry – and they need to be treated as such. The return from a method such as json() or assertStatus() is an instance of Illuminate\Http\Response and has no database methods.
Keep these things separate: make the HTTP request and check the response, then check the database.
$this
->withSession(['user_id' => $this->user_id])
->json('post', route('some_route'), $request)
->assertStatus($expected['code']);
$request['myuser_id'] = $this->user_id;
$this->assertDatabaseHas('profiles', $request);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With