Ian Rodrigues
Ian Rodrigues

Reputation: 743

Testing Laravel Eloquent Relationship

I'd like to know what's the best approach to ensure that my Activity model belongs to a User.

Activity.php

...

public function user()
{
   return $this->belongsTo(User::class);
}

How can I write a test that ensure that the Activity model has that relationship?

Upvotes: 1

Views: 1257

Answers (1)

Maraboc
Maraboc

Reputation: 11093

There is no problem in testing eloquent with the database as source of truth, so you can use the database like sqlite, for speed performances.

To test it create user with the factory and then create an activity attach it to the created user after that load the activity and test if it's linked with the created user.

We are following the pattern of Given, When, Then => Given you have u user When he create an activity (logged in, create a post ...) Then check if the created activity belongs to the given user ;)

Upvotes: 1

Related Questions