olimorris's avatar

How to test cookies in Laravel

I'm working on a custom blog site which will have posts that users can like. I ideally wish to limit users to 1 like per post and plan on enforcing this through the setting of a cookie.

Using TDD, I have the following test:

/** @test */
    public function a_person_can_only_like_a_post_once()
    {
        $this->withoutExceptionHandling();
        $this->expectException(AlreadyLikedException::class);

        // Create the post
        $post = factory('App\Post')->create();

        // Like the post
        $this->call('POST', '/posts/like/' . $post->slug);

        // Attempt to like the post again
        $this->call('POST', '/posts/like/' . $post->slug);

        $likes = Like::where('post_id', $post->id)->count();

        // Ensure that only one like exists
        $this->assertEquals($likes, 1);
    }

And in my LikeController.php I have the following method:

    public function create(Post $post)
    {
        if (Cookie::get('blog_post_liked_' . $post->id) !== null) {
            throw new AlreadyLikedException('Cannot like post more than once!');
        }

        Like::create([
            'post_id' => $post->id,
            'ip_address' => '127.0.0.1'
        ]);

        Cookie::queue('blog_post_liked_' . $post->id, 'true', 1);

        return response(200);
    }

When I run the tests I get Failed asserting that 1 matches 2.

My phpunit.xml file has:

    <php>
        <env name="APP_ENV" value="testing"/>
        <env name="DB_CONNECTION" value="testing"/>
        <env name="BCRYPT_ROUNDS" value="4"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="SESSION_DRIVER" value="file"/>
        <env name="QUEUE_CONNECTION" value="sync"/>
        <env name="MAIL_DRIVER" value="array"/>
    </php>

Any help would be gratefully appreciated.

0 likes
2 replies
ljpurcell's avatar

@Cronix very late to the party on this, but thank you for this comment. I had never thought about drawing inspiration from Laravel's code like this. Your suggestion is going to benefit me many times over. Thanks again!

Please or to participate in this conversation.