rafahsborges's avatar

What's the best approach to test those lines?

I've tested successfully these lines, but not the last part which could be an error.

public function store(FormRequestCalendar $request)
{
	$sanitized = $request->getSanitized();

        if ((new Calendar)->create($sanitized))
            return redirect()
                ->route('admin.calendars.index')
                ->with('success', 'Agenda criada com sucesso.');

        return redirect()
            ->back()
            ->with('error', 'Ocorreu um erro ao criar a agenda.');
}

What could I do to force the test to get into these lines?

public function store_returns_an_ok_response()
{
	$calendar = factory(Calendar::class)->make();
        $user = factory(User::class)->create();

        $auth = $this->post(route('login.login', ['cpf' => '000.000.000-00', 'senha' => '123456']));

        $data = [
            'nom_titulo_agenda' => $calendar->nom_titulo_agenda,
            'dat_inicio_evento' => $calendar->dat_inicio_evento->format('d/m/Y H:i'),
            'dat_fim_evento' => $calendar->dat_fim_evento->format('d/m/Y H:i'),
            'dsc_local' => $calendar->dsc_local,
            'dsc_url_anexo' => $calendar->dsc_url_anexo,
            'flg_ativo' => $calendar->flg_ativo,
        ];

        $response = $this->actingAs($user)->post(route('admin.calendars.store'), $data);

        $response->assertRedirect(route('admin.calendars.index'));
}

I've searched through lots of contents but could not make the test.

Thanks a lot!

0 likes
1 reply
bobbybouwmann's avatar

The last return will never be executed. Because when Calendar::create fails, it will throw an exception. So the only thing you can do is refactor your code for that

public function store(FormRequestCalendar $request)
{
    $sanitized = $request->getSanitized();

    try {
        Calendar::create($sanitized))
        
        return redirect()
            ->route('admin.calendars.index')
            ->with('success', 'Agenda criada com sucesso.');
    } catch (\Exception $exception) {
        return redirect()
            ->back()
            ->with('error', 'Ocorreu um erro ao criar a agenda.');
    }
}

Now you have the try-catch you can provide incorrect information and it could break.

However, in most cases creating a calendar item should always work, because you have the FormRequestCalendar in place which validates the required fields for you. So I don't see the reason why you need to add the error case here?

Please or to participate in this conversation.