如何在 Laravel 测试前设置 cookie?

How to set cookie before test in Laravel?

我需要根据 cookie 的存在测试特定行为,如何在发送请求(或访问页面)之前设置 cookie?目前以下失败,它的行为就像什么都没有设置。

$this->actingAs($user)
       ->withSession(['user' => $user, 'profile' => $profile]) ;
@setcookie( 'locale_lc', "fr", time() + 60 * 60 * 24 * 900, '/', "domain.com", true, true) ;
$this->visit('/profile') ;

或者

$cookie = ['locale_lc' => Crypt::encrypt('fr')] ;

$this->actingAs($user)
         ->withSession(['user' => $user, 'profile' => $profile])
         ->makeRequest('GET', '/profile', [], $cookie) ;

问题出在cookie的设置和读取上。 @setcookie$_COOKIE 都不能在测试上下文中工作。使用 cookie 数组的方法 makeRequest 是正确的。

但是!

读取脚本(控制器,中间件)必须使用Laravel的$request->cookie()方法,而不是直接尝试使用$_COOKIE访问它。在我的例子中,cookie 需要被我们域上的另一个应用程序读取,所以我还必须禁用该特定 cookie 的加密,这可以在 EncryptCookies.php

中完成

EncryptCookies

<?php

protected $except = [
        'locale_lc'
    ];

测试

<?php

$cookie = ['locale_lc' => 'fr'] ;

$this->actingAs($user)
         ->withSession(['user' => $user, 'profile' => $profile])
         ->makeRequest('GET', '/profile', [], $cookie) ;

中间件

<?php

public function handle($request, Closure $next){
  if($request->cookie('locale_lc')){...}
}