When writing tests Uncle Bob says we should only write the minimum of code to make the test pass. In my case bellow where I have the test, controller and service, it is not what happened, but I don't know how to make it different. As you can see, my test tests if a logged user can create a group: it's simply the action of storing a group (name, status and relation to a modules table) on the database, as my service makes clear, but in my service I am doing more than just creating the group, I am also checking if there's no errors to the queries and wrapping everything on a try-catch block. That seems more than just one thing, it seems like two or even three. The point is: by adding more behaviour to a function than what the test tests makes the test not cover everything it says it does, so what would be a solution for this?
/** @test */
public function a_logged_user_can_create_a_group()
{
$this->withoutExceptionHandling()->signIn();
$group_data = [
'name' => $this->faker->word(),
'status' => $this->faker->boolean(),
];
$modules = ['modules' => Modules::factory(1)->create()->pluck('id')];
$response = $this->post(route('cms.groups.store'), array_merge($group_data, $modules));
$response->assertSessionHas('message', trans('cms.groups.success_create'));
}
public function store(GroupRequest $request)
{
$result = $this->group_service->createGroupWith($request->all());
return redirect()->back()->with('message', $result['msg']);
}
public function createGroupWith($data)
{
try {
DB::beginTransaction();
$modules_id = array_pop($data);
$group = Group::create($data);
$group->modules()->attach($modules_id);
DB::commit();
return ['msg' => trans('cms.groups.success_create')];
} catch (\Throwable $error) {
DB::rollBack();
return ['msg' => $error->getMessage()];
}
}