jaycito's avatar

Setting cookies before test

I know neither setcookie nor sessions in general are very test-friendly, I need to test a specific behaviour based on the presence of a cookie, how do I set a cookie before running the test ? For the moment it fails, it behaves likes nothing was set.

Is there a way using ->visit() that I'm not aware of or a way with ->call() where I can set session variables ?

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

I also tried this, but it does nothing

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

$this->actingAs($user)
         ->withSession(['user' => $user, 'profile' => $profile])
         ->makeRequest('GET', '/profile', [], $cookie) ;
0 likes
4 replies
jaycito's avatar

@SaeedPrez that's not quite what I want to test though, I don't want an internal page to set the cookie, the test is sharing the cookie between this application and another, hence the need to set it before the test starts

SaeedPrez's avatar
Level 50

@jaycito

  1. look at this, the 4th argument. Not sure if it's changed in 5.2, but worth a try.

  2. this is also worth reading.

  3. You could probably also use PHP´s `$_COOKIE['key'] = 'value' but this won't go through Laravel and won't be encrypted

That's all I have, maybe someone else knows a better solution..

1 like
jaycito's avatar

@SaeedPrez thanks, finally got it working. Your #2 was helpful, but I had to tweak my middleware further to get it working, what a bizarre issue.

1 like

Please or to participate in this conversation.