我最近在用laravel尝试TDD,我想Assert重定向是否将用户带到具有整数参数的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+');
中的参数视为regex,然后传递任何url,如/projects/1
,到目前为止,它以数字结尾,但它将其视为原始字符串,并期望/^projects/\d+
的url
我会很感激你的帮助。
3条答案
按热度按时间pexxcrt21#
在看了Jeffery Way的教程后,他谈到了如何处理这个问题。他是这样解决问题的
字符串
vtwuwzda2#
这是不可能的。您需要使用正则表达式测试响应中的
Location
头。这是一个问题,因为您不能使用当前路由名称.这就是为什么我做了两个函数来增加测试的可读性。你将像这样使用这个函数:
字符串
这就是实现。
型
2ul0zpep3#
您可以从响应头中获取
Location
值,并以这种方式进行匹配字符串