gerardw85's avatar

Unit Test - Newbie Question

Hi, Very new here, and working through an online tutorial - but I'm stuck. Hopeful the community can point me in the right direction.

I have this Unit Test:

public function test_StoreValid()
    {
        $params = [
            'title' => 'Valid Title',
            'content' => 'At least 10 characters'
        ];

        $this->post('/posts', $params)
            ->assertStatus(302)
            ->assertSessionHas('status');
        
        $this->assertEquals(session('status'), 'The blog post was created!');

I have this Route: route::resource('posts', PostsController::class);

The Unit Test is successfully creating the post and everything is working as intended - but I don't know why it's working. $this->post('/posts', $params) The /posts route takes you to a view that only displays posts - no ability to create a post there. To create one you'd need to navigate to /posts/create. I'm totally lost as to how the above Unit Test is able to create the test post since it's not being pointed to /posts/create.

0 likes
3 replies
tykus's avatar
tykus
Best Answer
Level 104

You are making a POST request to the /posts endpoint - that is distinct from a GET request which reads the Resource.

The post method is a convenience which defers to the call method; which might make the intention clearer:

$this->call('POST', '/posts', $params)
1 like
gerardw85's avatar

Thanks for the fast answer - and it helped. After reading I ran route:list in terminal and was able to tie this together in my head now seeing the posts URI has the POST method, which goes to this action App\Http\Controllers\PostsController@store. Makes sense now.

Please or to participate in this conversation.