3

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.

7
  • What's the result of dd($request);? Commented May 19, 2018 at 13:33
  • $request is just an associative array ['id' => 2 , 'name' => 'test' , ....] @JonasStaudenmeir Commented May 19, 2018 at 13:36
  • What's your exact Laravel version? Commented May 19, 2018 at 13:40
  • 5.4.36 @JonasStaudenmeir Commented May 19, 2018 at 13:58
  • Do you get the same error with PHPUnit 5.*? Commented May 19, 2018 at 14:01

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

This is actually the correct answer and should be accepted as the accepted one. Original post please review and change.
0

I upgraded my laravel version from 5.4.37 to 5.5.40 and problem solved. assertDatabaseHas() works fine now.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.