Are you making sure that the authenticated user is leaving the reply inside your controller? It looks like your Reply factory also creates a thread?
Why is assertDatabaseHas failing in this test case?
Here's my test case
public function an_authenticated_user_may_participate_in_forum() {
$this->withoutExceptionHandling(); // Disable exception handling. Throw the exception at right place
$user = factory('App\User')->create();
$this->be($user);
$thread = factory('App\Thread')->create(); // Thread ID 1
$reply = factory('App\Reply')->make();
$this->post($thread->path() . '/replies', $reply->toArray());
$this->get($thread->path())
->assertSee($reply->body);
$this->assertDatabaseHas('replies', $reply->toArray());
}
The test works fine if I comment out the last line $this->assertDatabaseHas('replies', $reply->toArray());
Here's what phpUnit says:
Failed asserting that a row in the table [replies] matches the attributes {
"user_id": 3,
"thread_id": 2,
"body": "Sint labore animi id hic blanditiis eius consequatur temporibus."
}.
Found: [
{
"id": "1",
"user_id": "1",
"thread_id": "1",
"body": "Sint labore animi id hic blanditiis eius consequatur temporibus.",
"created_at": "2017-10-27 13:03:35",
"updated_at": "2017-10-27 13:03:35"
}
].
It's apparent that a new thread is being created; but I can't figure out where and how. Would really appreciate your help.
Your $reply in the assertion is using the values that the factory whipped up for the user and thread it created. It does not know about the values that the request created.
Really the reply request will only have a body - I don't know why you would want to make a Role from the factory for this. Simulate the actual request payload, which will not have a user_id or thread_id
Hiding the content of the reply doesn't benefit you at all, be explicit about what you expect to see, e.g.
public function an_authenticated_user_may_participate_in_forum()
{
$user = factory('App\User')->create();
$this->be($user);
$thread = factory('App\Thread')->create();
$this->post($thread->path() . '/replies', [
'body' => 'This is my awesome reply'
]);
$this->get($thread->path())->assertSee($reply->body);
$this->assertDatabaseHas('replies', [
'thread_id' => $thread->id,
'user_id' => $user->id,
'body' => 'This is my awesome reply'
]);
}
Please or to participate in this conversation.