From 85eab4f015cb7912126c07faaaca819170e34371 Mon Sep 17 00:00:00 2001 From: Nafies Luthfi Date: Mon, 26 Jun 2017 10:45:24 +0800 Subject: [PATCH] Added person father, mother and childs relation --- app/User.php | 18 ++++++++++++++++++ tests/TestCase.php | 12 +++++++++++- tests/Unit/PersonRelationsTest.php | 22 +++++++++++++++++++--- 3 files changed, 48 insertions(+), 4 deletions(-) diff --git a/app/User.php b/app/User.php index 2d916f8..040fe28 100644 --- a/app/User.php +++ b/app/User.php @@ -54,4 +54,22 @@ class User extends Authenticatable return false; } + + public function father() + { + return $this->belongsTo(User::class); + } + + public function mother() + { + return $this->belongsTo(User::class); + } + + public function childs() + { + if ($this->gender_id == 2) + return $this->hasMany(User::class, 'mother_id'); + + return $this->hasMany(User::class, 'father_id'); + } } diff --git a/tests/TestCase.php b/tests/TestCase.php index 2932d4a..b55950f 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -2,9 +2,19 @@ namespace Tests; -use Illuminate\Foundation\Testing\TestCase as BaseTestCase; +use Laravel\BrowserKitTesting\TestCase as BaseTestCase; abstract class TestCase extends BaseTestCase { use CreatesApplication; + + protected $baseUrl = 'http://localhost'; + + protected function loginAsUser() + { + $user = factory(User::class)->create(); + $this->actingAs($user); + + return $user; + } } diff --git a/tests/Unit/PersonRelationsTest.php b/tests/Unit/PersonRelationsTest.php index ca35120..5087da0 100644 --- a/tests/Unit/PersonRelationsTest.php +++ b/tests/Unit/PersonRelationsTest.php @@ -15,7 +15,7 @@ class PersonRelationsTest extends TestCase { $person = factory(User::class)->create(); - $this->assertDatabaseHas('users', [ + $this->seeInDatabase('users', [ 'nickname' => $person->nickname, 'gender_id' => $person->gender_id, ]); @@ -28,10 +28,12 @@ class PersonRelationsTest extends TestCase $father = factory(User::class)->states('male')->create(); $person->setFather($father); - $this->assertDatabaseHas('users', [ + $this->seeInDatabase('users', [ 'id' => $person->id, 'father_id' => $father->id, ]); + + $this->assertEquals($father->name, $person->father->name); } /** @test */ @@ -41,9 +43,23 @@ class PersonRelationsTest extends TestCase $mother = factory(User::class)->states('female')->create(); $person->setMother($mother); - $this->assertDatabaseHas('users', [ + $this->seeInDatabase('users', [ 'id' => $person->id, 'mother_id' => $mother->id, ]); + + $this->assertEquals($mother->name, $person->mother->name); + } + + /** @test */ + public function person_can_many_childs() + { + $mother = factory(User::class)->states('female')->create(); + $person = factory(User::class)->create(); + $person->setMother($mother); + $person = factory(User::class)->create(); + $person->setMother($mother); + + $this->assertCount(2, $mother->childs); } }