Skip to content

Instantly share code, notes, and snippets.

@jasonlbeggs
Created March 5, 2021 01:25
Show Gist options
  • Save jasonlbeggs/a0d023d99d9e6b7022e1daec701a406d to your computer and use it in GitHub Desktop.
Save jasonlbeggs/a0d023d99d9e6b7022e1daec701a406d to your computer and use it in GitHub Desktop.

from() Testing Helper

When testing with Laravel, sometimes it's helpful to test that a user was redirected back to the page where they "submitted" the form from.

Normally, if you just call $this->post('/some-endpoint')->assertRedirect('/some-endpoint');, the test will fail because the session doesn't have a previous page set.

To fix this issue, Laravel provides a from() testing helper that, under the hood, sets a referer header and sets the _previous.url session variable to the url you pass in. Then, when you call redirect()->back() in your controller or somewhere else, Laravel knows where to redirect the user to.

/** @test */
public function the_user_is_redirected_back_to_the_edit_page()
{
    $user = User::factory()->create();
    $post = Post::factory()->create();
    
    $data = ['title' => 'Paul is Eric and Eric is Paul'];
    
    $this->actingAs($user)
        ->from('/posts/1/edit')
        ->patch('/posts/1', $data)
        ->assertRedirect('/posts/1/edit');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment