php - 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+
我会很感激任何帮助。
解决方案
看了 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);
推荐阅读
- php - 无法从 MySQL 中删除行
- php - 使用 htaccess 规则将 API 路径重定向到 Slim Routes
- powershell - 为什么我的 PowerShell 脚本不遵守步骤顺序?
- apache-kafka - 领导者更改后,Spring kafka 消费者不提交到 kafka 服务器
- django - Django 设计模型 - 当状态字段的数据发生变化时,其余模型状态随之变化
- javascript - 在 Express.JS 中呈现页面之前的异步请求
- javascript - 无法从 JS 中的文件中提取 XML 节点值 - 它打印为“未定义”
- c - 如何使用 libcurl + POST 上传文件?
- vb.net - 将值与 3 种状态 Y/N 比较为 String 或 DbNull
- c++ - C++ 反转迭代器