Regenerating Cart from a Cookie

Posted 5 months ago by Roni

Hey, I keep circling back to testing Cookies. I haven't had to use them since I started using TDD, and I feel like I'm missing something.

Right now, I'm trying to perform this test on a middleware that should for guests force a cart on the session.

Using this criteria...

  1. If there is a cart on the session, simply update the expiry of the cookie so it's lifetime is reset.
  2. if there isn't a cart on the session, but there is a session_id stored on the cookie in the cart key, then restore that session (or restore the cart portion of the session, right now . I'm just doing the whole thing, but if you know how to do both options please let me know).
  3. if neither is present (first time on the site) set the session and the cookie.

For clarity I'm using

Illuminate\Support\Facades\Cookie; when referencing Cookie::get()

here is the failing unit test: lots of dumps for clarity, the output will fail and show two different cart objects

   /** @test */

    public function a_guest_cart_is_regenerated_when_they_come_back_to_the_site() {
        $response = $this->get('/');
        $oldCart = session('cart');
        $response = $this->get('/');
        $newCart = session('cart');
        $this->assertInstanceOf(Cart::class, session('cart'));

        $this->assertSame($oldCart, $newCart);

Here is the middleware, which is working, for the no session or cookie phase. Middleware is firing correctly (registered) and routes are properly enclosed in a middleware group. I left all my hacking in there commented out


namespace App\Http\Middleware;

use App\Orders\Cart;
use Closure;
use Illuminate\Support\Facades\Cookie;

class SessionHasCart
     * Handle an incoming request.
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
    public function handle($request, Closure $next)

        if(Cookie::has('cart') && ! session()->has('cart')) {
        } elseif(! session()->has('cart')) {
            session()->put('cart', new Cart());

//        $cookie = Cookie::make('cart',session()->getId(),Cart::LIFETIME);
//        dd($cookie);

        return $next($request); //->cookie('cart',session()->getId(),Cart::LIFETIME));

Also phpunit.xml is treating sessions and cookies as arrays

        <env name="APP_ENV" value="testing"/>
        <env name="BCRYPT_ROUNDS" value="4"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="QUEUE_DRIVER" value="sync"/>
        <env name="MAIL_DRIVER" value="array"/>
        <env name="DB_CONNECTION" value="sqlite"/>
        <env name="DB_DATABASE" value=":memory:"/>

Any advice appreciated

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.