【问题标题】:How to set cookie before test in Laravel?如何在 Laravel 测试前设置 cookie?
【发布时间】:2016-09-23 07:54:21
【问题描述】:

我需要根据 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) ;

【问题讨论】:

    标签: testing cookies laravel-5 phpunit


    【解决方案1】:

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

    但是!

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

    中完成

    加密Cookies

    <?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')){...}
    }
    

    【讨论】:

    • 如果您没有禁用加密,这仍然有效吗?
    猜你喜欢
    • 1970-01-01
    • 2016-03-17
    • 2017-12-05
    • 2012-12-09
    • 1970-01-01
    • 2021-01-29
    • 2019-12-09
    • 2013-10-19
    • 1970-01-01
    相关资源
    最近更新 更多