I have a middleware that creates cookies for guest users and I'm struggling to test it. This is my middleware's handle
function:
public function handle($request, Closure $next)
{
$guestCookieKey = 'guest';
if ($request->cookie($guestCookieKey)) {
return $next($request);
}
return $next($request)->cookie($guestCookieKey, createGuestCookieId());
}
Testing this on the browser works perfectly: when request hasn't this cookie, it creates a new one. When it does have it, we just forward the request chain.
The problem is while testing this. Here's what I'm doing:
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\TestResponse;
class GuestCookieTest extends TestCase
{
public function testItCreatesOnlyOneCookiePerResponse()
{
$firstResponse = $this->get('/');
$secondResponse = $this->get('/');
$this->assertEquals(
$firstResponse->headers->getCookies()[0],
$secondResponse->headers->getCookies()[0]
);
}
}
The error shows diffs between the two values:
Failed asserting that two objects are equal.
--- Expected
+++ Actual
@@ @@
Symfony\Component\HttpFoundation\Cookie Object (
'name' => 'guest'
- 'value' => 'eyJpdiI6IkttV2I2dldNelNkWXpyQXRWRUFlRUE9PSIsInZhbHVlIjoiQnBFYVlZNTNtYThjOWFxTTdLRXh4Zz09IiwibWFjIjoiZjY0NmEyNTMyMmM2MjJkNThmNmM5NWMxMDc2ZThmOTZjNDJhZTJjMmJhMGM0YTY0N2Q4NDg5YWEwNjI1ODEwZiJ9'
+ 'value' => 'eyJpdiI6InRSMUVOSEZESm5xblwvOUU3aHQweGZ3PT0iLCJ2YWx1ZSI6ImhjU1lcL2pJUU1VbGxTN1BJQTdPWXBBPT0iLCJtYWMiOiJmM2QyYjQ3NzU5NWU5Nzk2Yjg0Yzg4MmFlNGFmYTdkNThlNjZhNzVhMjE3YjUxODhlNzRkMjA0MWQzZmEyODM2In0='
'domain' => null
'expire' => 0
'path' => '/'
It's like $this->get
was not executed in the same environment (?), not preserving cookies set previously and creating unique calls and data for each call. This does make sense, but how would you test the creation of a guest cookie if no other with the same name is set?