Dmitry
Dmitry

Reputation: 59

Database entry not saved during unit tests when mocked request

$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?

Upvotes: 1

Views: 1482

Answers (2)

AbdullahHejazi
AbdullahHejazi

Reputation: 312

The make method doesn't save the post to the database, it just creates the model. Use the create method instead to save it to the database.

Change this:

$post= factory(Model)->make();

To this:

$post= factory(Model)->create();

Upvotes: 0

Ben
Ben

Reputation: 2255

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.

Upvotes: 1

Related Questions