ramirushi7997's avatar

What is the correct way to test the eloquent models and relationships?

Hello everyone, I am relatively new to Laravel and testing. I wondered the correct way to test the eloquent model and its relationships. I have played around for a while and made these tests below for relationships. But it feels like this should not be an excellent way to test things.

<?php

namespace Models;

use App\Models\User;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Tests\TestCase;

class UserTest extends TestCase
{
    /**
     * @test
     * @void
     */
    public function user_belongs_to_organization()
    {
        $user = new User();
        $this->assertInstanceOf(BelongsTo::class, $user->organization());
    }

    /**
     * @test
     * @void
     */
    public function user_has_many_user_answers()
    {
        $user = new User();
        $this->assertInstanceOf(HasMany::class, $user->userAnswers());
    }
}

If you know any better testing methods for models and relationships, please let me know in the comment section below. I would love to hear more on that.

Thanks.

0 likes
1 reply
axeloz's avatar

First you wanna seed data with Factories. For instance:

$user = User::factory()->ForCompany()->hasAnswers()->create();

https://laravel.com/docs/9.x/database-testing#defining-model-factories

Then you should assert existence:

$this->assertDatabaseHas('users', [
'email'		=> # the email you used to create your user
'name'		=> # the name of the user
]);

And same for Organisation and so on.

Please or to participate in this conversation.