Last active
April 28, 2022 08:09
-
-
Save tonyfrenzy/c36236da38c751b42acfeacc123a1601 to your computer and use it in GitHub Desktop.
belongsTo() Relationship Test (Post-Comment) - Testing Model Relationships in Laravel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Tests\Unit; | |
use App\Comment; | |
use App\Post; | |
use App\User; | |
use Illuminate\Foundation\Testing\RefreshDatabase; | |
use Illuminate\Foundation\Testing\WithFaker; | |
use Illuminate\Support\Facades\Schema; | |
use Tests\TestCase; | |
class CommentsTest extends TestCase | |
{ | |
use RefreshDatabase, WithFaker; | |
/** @test */ | |
public function comments_database_has_expected_columns() | |
{ | |
$this->assertTrue( | |
Schema::hasColumns('comments', [ | |
'id','user_id', 'post_id', 'body' | |
]), 1); | |
} | |
/** @test */ | |
public function a_comment_belongs_to_a_post() | |
{ | |
$user = factory(User::class)->create(); | |
$post = factory(Post::class)->create(['user_id' => $user->id]); | |
$comment = factory(Comment::class)->make(['post_id' => $post->id]); | |
// Method 1: Test by count that a comment has a parent relationship with post | |
$this->assertEquals(1, $comment->post->count()); | |
// Method 2: | |
$this->assertInstanceOf(Post::class, $comment->post); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
I got wrong results on
$this->assertEquals(1, $comment->post->count());
, because $comment->post is object not a collection. I suggesting to change it$this->assertEquals(1, $comment->post()->count());