Search code examples
phpregexlaraveltddassert

Laravel assert redirect with regular expression


I am newly trying out TDD with laravel, and I want to assert if a redirect took a user to a url that has an integer param. I wonder if I could use regex to catch all positive integers.

I'm running this app with the laravel 5.8 framework and I know that the url parameter is 1 because I refresh the database each for each test, so setting the redirect url as /projects/1 works but this sort of hardcoding feels weird.

I've attached a block of code I tried using regex for but this doesn't work

 /** @test */
    public function a_user_can_create_projects()
    {
        // $this->withoutExceptionHandling();

        //If i am logged in
        $this->signIn(); // A helper fxn in the model

        //If i hit the create url, i get a page there
        $this->get('/projects/create')->assertStatus(200);

        // Assumming the form is ready, if i get the form data
        $attributes = [
            'title' => $this->faker->sentence,
            'description' => $this->faker->paragraph
        ];

        //If we submit the form data, check that we get redirected to the projects path
        //$this->post('/projects', $attributes)->assertRedirect('/projects/1');// Currently working
        $this->post('/projects', $attributes)->assertRedirect('/^projects/\d+');

        // check that the database has the data we just submitted
        $this->assertDatabaseHas('projects', $attributes);

        // Check that we the title of the project gets rendered on the projects page 
        $this->get('/projects')->assertSee($attributes['title']);

    }

I expected the test to treat the argument in assertRedirect('/^projects/\d+'); as regex and then pass for any url like /projects/1 so far it ends in a number, but it takes it as a raw string and expects a url of /^projects/\d+

I'd appreciate any help.


Solution

  • After watching a tutorial by Jeffery Way, he talked about handling this issue. Here's how he solves the situation

    //If we submit the form data, 
    $response = $this->post('/projects', $attributes);
    
    //Get the project we just created
    $project = \App\Project::where($attributes)->first();
    
    // Check that we get redirected to the project's path
    $response->assertRedirect('/projects/'.$project->id);