首页 > 解决方案 > Laravel 使用正则表达式断言重定向

问题描述

我最近正在尝试使用 laravel 进行 TDD,并且我想断言重定向是否将用户带到具有整数参数的 url。我想知道是否可以使用正则表达式来捕获所有正整数。

我正在使用 laravel 5.8 框架运行此应用程序,并且我知道 url 参数为 1,因为我为每个测试都刷新了数据库,因此将重定向 url 设置为/projects/1有效,但这种硬编码感觉很奇怪。

我附上了一段我尝试使用正则表达式的代码,但这不起作用

 /** @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']);

    }

我希望测试将参数assertRedirect('/^projects/\d+');视为正则表达式,然后传递任何 url,就像/projects/1到目前为止它以数字结尾一样,但它将它作为原始字符串并期望 url/^projects/\d+

我会很感激任何帮助。

标签: phpregexlaraveltddassert

解决方案


看了 Jeffery Way 的教程后,他谈到了如何处理这个问题。这是他解决问题的方法

//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);

推荐阅读