Laravel 5如何测试重定向

时间:2016-03-30 13:57:14

标签: php laravel-5 phpunit

我有一个Laravel 5应用程序,其中一个控制器操作通过重定向到Laravel应用程序之外的页面但在同一个域上完成。手动与页面交互工作正常,但使用PHPunit自动化测试并不是。它不断尝试加载路线,并且已经发送'标题失败了。

路线

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

更新

它似乎与Web中间件有关,更具体地说是CSRF中间件,干扰了我的重定向标头。指定use WithoutMiddleware;也会禁用会话,如何保持会话但在测试上下文中禁用CSRF?

更新2

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

1 个答案:

答案 0 :(得分:0)

在流程隔离中运行测试或整个套件最终似乎可以工作。可能通过更新phpunit进行了改进,因为以前没有效果。

通过命令行运行:

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

或者在phpunit.xml中:

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

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

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