Laravel 5 如何测试重定向

Laravel 5 how to test redirect

我有一个 Laravel 5 应用程序,其中一个控制器操作通过重定向到 Laravel 应用程序之外但在同一域中的页面来完成。手动与页面交互工作正常,但使用 PHPunit 自动化测试则不行。它一直尝试加载路线并失败 'headers already sent'.

路线

Route::post('/trials', [
    'middleware' => ['web'],
    'uses' => 'TrialsController@create'
]);

控制器

public function create(Request $request)
{
  ...
  setcookie( 'etc', $value, time() + 60, '/', "domain.com", true, true) ;
  return Saml2::login('https://store.domain.com');
}

测试

public function testSuccessfulSignup(){

    $this->visit('/signup')
        ->type('test@mail.com', 'mail')
        ->type('Philip', 'first_name')
        ->type('Fry', 'last_name')
        ->press('Signup !') ;
        // ->seePageIs('https://store.domain.com'); doesn't work
        // ->assertRedirectedTo('https://store.domain.com'); doesn't work
}

错误

1) TrialsTest::testSuccessfulSignup
A request to [http://domain.com/trials] failed. Received status code [500].

/private/var/identity/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:196
/private/var/identity/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:80
/private/var/identity/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:114
/private/var/identity/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:554
/private/var/identity/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:541
/private/var/identity/tests/TrialsTest.php:154

Caused by
exception 'ErrorException' with message 'Cannot modify header information - headers already sent by (output started at phar:///usr/local/bin/phpunit/phpunit/Util/Printer.php:134)' in /private/var/identity/app/Http/Controllers/TrialsController.php:84

更新

这似乎与网络中间件有关,更具体地说是 CSRF 中间件,干扰了我的重定向 headers。指定 use WithoutMiddleware; 也会禁用 Session,如何保留 session 但在测试上下文中禁用 CSRF?

更新 2

关于接近投票:你可以在测试代码中看到我断言它应该遵循重定向,我希望这段代码做的是遵循控制器操作之外的重定向(成功而不是失败)然后继续做更多的验证。

运行 进程隔离中的测试或整个套件似乎终于可以工作了。这可能已经通过更新 phpunit 得到改善,因为它以前没有效果。

通过命令行运行:

phpunit --process-isolation --filter <method>

或在 phpunit.xml:

<phpunit ...
         processIsolation="true"
         stopOnFailure="false">
<testsuites>
</testsuites>
</phpunit>

显然测试代码也需要期待重定向。

$this->doStuff()
     ->assertRedirect($url);