Ad

Database Entry Not Saved During Unit Tests When Mocked Request

- 1 answer

$post= factory(Model)->make();
$this->post(route("post.store", $post->toArray()))->assertSee($model->name);
$this->assertDatabaseHas($this->table, $model->toArray());

This code works. But if we mocked request:

$this->mock(PostRequest::class, function ($mock) {
   $mock->shouldReceive('passes')->andReturn(true);
});

in this case an empty database error is returned

The table is empty..

Blockquote

How can this be?

Ad

Answer

You don't have anything in the database, as you are actually not persisting anything there. I suppose that in post.store controller you have logic for persisting that model, and that's why it passes.

In your mock, you don't persist anything to the database, you just basically say, receive passes and return true and nothing else happens, therefore, nothing is saved to the database, which is the reason why $this->assertDatabaseHas($this->table, $model->toArray()); will tell you that model is not persisted, as it tests against the test database content.

Hope this helps.

Ad
source: stackoverflow.com
Ad