How to test if relationship has successfully created?

Posted 2 years ago by leandromatos

In a test case, how to test if relationship has successfully created?



use App\School;
use App\Teacher;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class TeacherTest extends TestCase
    use DatabaseTransactions;

    /** @test */
    public function a_teacher_can_be_created()
        // Given
        // create a teacher
        $teacher = Teacher::create([
            'name'     => 'Albert Einstein',
            'email'    => '[email protected]',
            'password' => bcrypt(123),

        // add school to teacher
        $schools = factory(School::class, 2)->create();

        // Wheen
        // get a latest teacher
        $latestTeacher = Teacher::latest()->first();

        // Then
        // assert equals: teacher is equal latest teacher
        $this->assertEquals($teacher->id, $latestTeacher->id);
        $this->assertEquals('Albert Einstein', $latestTeacher->name);
        $this->assertEquals('[email protected]', $latestTeacher->email);

        // ?????????? assert $teacher belongs to $school ??????????

        // see a teacher in database
        $this->seeInDatabase('teachers', [
            'name'  => 'Albert Einstein',
            'email' => '[email protected]',

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.