For stuff like this, I like to see how Laravel is doing it in their tests. Here are the cookie tests: https://github.com/laravel/framework/blob/5.7/tests/Cookie/CookieTest.php
Nov 11, 2018
2
Level 8
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.
Please or to participate in this conversation.