Laravel断言重定向忽略查询参数

时间:2019-02-22 17:35:42

标签: php laravel testing assertion

我有一个api测试,可以断言是否重定向到特定路由。问题是重定向URL的查询参数包括更改的时间戳。想知道Laravel的断言是否可以使用assertRedirect方法的替代方法来忽略查询参数。

/** @test */
    public function test_can_redirect()
    {

        $this->call('GET', "users/auth")
            ->assertRedirect('http://localhost:8000/dashboard?timestamp=1550848436');
    }

我要声明重定向到

http://localhost:8000/dashboard

不是

http://localhost:8000/dashboard?timestamp=1550848436

2 个答案:

答案 0 :(得分:0)

测试代码背后的原理是确保正在发生的事情是预期的,因此,如果您期望时间戳的查询参数,为什么不也建立它呢?

/** @test */
    public function test_can_redirect()
    {
        $url = "/dashboard";
        // http://php.net/manual/en/function.time.php
        $timestamp = time();

        $this->call('GET', "users/auth")
            ->assertRedirect($url . '?timestamp=' . $time);
    }

答案 1 :(得分:0)

您可以使用getTargetUrl提取没有查询字符串的内容。

public function test_can_redirect()
{
    $redirectUrl = 'http://localhost:8000/dashboard';
    $res = $this->getJson('users/auth')->assertStatus(302); # Check if redirection
    # Or you could use this: $this->assertTrue($res->isRedirection());
    $parts = explode('?', $res->getTargetUrl());
    $this->assertTrue($parts[0] === $redirectUrl); # parts[0] is the url 
wihtout query string

    # If you want to check the keys of query string, too
    $this->assertTrue(count($parts) === 2);  # check query string exists
    parse_str($parts[1], $query);
    $this->assertArrayKeys($query, ['time', ..., 'the key you want to check']);
}

protected function assertArrayKeys(array $array, array $checks) 
{
    $keys = array_keys($array);
    foreach ($checks as $check) {
        $this->assertTrue(in_array($check, $keys));
    }
}