James_Moore's avatar

When redirecting back after mail sent in test 302 status code

I have the following test


    /** @test */
    public function an_authenticated_user_can_email_an_ad_creator()
    {
	// Given
        \Mail::fake();

        \Mail::assertNothingSent();

        $ad = factory(Ad::class)->create();

        $creator = $ad->creator;

        $this->signIn();
	
	// When
        $this->post("/contact/ads/{$ad->id}", ['body' => "Hello are you selling any golf clubs"])->assertSuccessful();
	
	// Then
        \Mail::assertSent(ContactAdCreator::class, function ($mail) use ($creator) {
            return $mail->hasTo($creator->email);
        });
    }

Controller

class ContactAdCreatorController extends Controller
{
    public function store(Ad $ad)
    {
        request()->validate(['body' => 'required']);

        Mail::to($ad->creator->email)
            ->send(new ContactAdCreator(request()->body));

        return redirect()->back()
            ->with(['message' => 'Email sent!']);
    }
}

When I include the block

return redirect()->back()
->with(['message' => 'Email sent!']);

The test fails why ?

0 likes
3 replies
bobbybouwmann's avatar
Level 88

It fails because of this line

->assertSuccessful();

This asserts if the HTTP status code is between 200 and 299. However, redirect()->back() is a redirect which gives you a HTTP status code of 302. So instead, you need to do this

$this->post("/contact/ads/{$ad->id}", ['body' => "Hello are you selling any golf clubs"])
    ->assertRedirect("/contact/ads/{$ad->id}");
1 like

Please or to participate in this conversation.