The test code be written in the test sheet and to create a test you should run this command
php artisan make:Test TestName press enter and then write this code into your test file.
the test name should be start from test_a_group_has_many_modules() like this...
Naming a test and witing what it says.
I am currently learning TDD and I found that one of the biggest difficulties is o know if you are testing what your test says you are.
For example, I have a test bellow that states I am testing a group has many modules and its code simply adds modules to a group and then checks if every module is really a module.
public function a_group_has_many_modules()
{
$modules = Modules::factory(10)->create();
$group = Group::factory()->create();
$group->modules()->attach($modules);
foreach ($modules as $module) {
$this->assertInstanceOf(Modules::class, $group->modules()->where('module_id', $module->id)->first());
}
}
It all seems a bit weird because it seems I am actually writing code that should be on a Controller and not on a test. That's why I am having doubts such as "is the name incorrect or the code?", "maybe I wanted to test if the relations between the tables are correct?", "should I just not worry much and go on step by step because, after all, I am learning it yet?".
Can someone help me clear it out?
And why do you need 10 Module instances to prove this is the case?
You can make the association between the Models using the Factory has method https://laravel.com/docs/9.x/eloquent-factories#many-to-many-relationships. Then simplify the test to ensure that (i) you get an Eloquent Collection and (ii) each item in the Collection is a Module instance.
public function a_group_has_many_modules()
{
$group = Group::factory()->has('modules', 1)->create();
$this->assertInstanceOf(Collection::class, $group->fresh()->modules);
$this->assertInstanceOf(Module::class, $group->modules->first());
}
I don't often write tests that prove Eloquent relationships exist - IMHO their value is limited compared with feature tests that prove the relationship exists.
Please or to participate in this conversation.