jonassiewertsen's avatar

Unit Test for Morph many to many

Hej

I am looking for an elegant way for a Unit test.

my database is looking like:

categories
- id 
- name

desks
- id
- name
- something else

categoryable
- categorie_id
- categoryable_id
- categoryable_type

The morph relations itself are working. Now im pulling some arrays from the collections to test via assertEquals, which seems like a really ugly way of doing it.

$this->assertEquals()

Is there something similar way like assertInstanceOf, just for many to many relations?

$this->assertInstanceOf()
0 likes
2 replies
D9705996's avatar

For a unit test you could still use assertInstanceOf e.g.


$desk = new Desk();

$this->assertInstanceOf(
  'Illuminate\Database\Eloquent\Relations\MorphMany',
  $desk->categoryable()
);

Rinse and repeat for your other relationships. I'm 99% sure that I've used the correct class above but you might need to tweak

You can find the relation types in the API documentation

https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Relations.html

jonassiewertsen's avatar
Level 14

@D9705996 - Thanks for the right direction!

Actually i'm asserting for a plain Collection. It's working and looking clean.


$desk = create('App\Desk');

$this->assertInstanceOf(
   'Illuminate\Database\Eloquent\Collection', 
   $desk->categories
);

Please or to participate in this conversation.