Skip to content

Commit b68ee0c

Browse files
author
Piotr Jura
committed
#211 Testing auth failure, correct storing and validation errors
1 parent 23e266a commit b68ee0c

File tree

2 files changed

+50
-7
lines changed

2 files changed

+50
-7
lines changed

tests/Feature/ApiPostCommentsTest.php

Lines changed: 42 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,7 @@ class ApiPostCommentsTest extends TestCase
1414

1515
public function testNewBlogPostDoesNotHaveComments()
1616
{
17-
factory(BlogPost::class)->create([
18-
'user_id' => $this->user()->id
19-
]);
17+
$this->blogPost();
2018

2119
$response = $this->json('GET', 'api/v1/posts/1/comments');
2220

@@ -27,9 +25,7 @@ public function testNewBlogPostDoesNotHaveComments()
2725

2826
public function testBlogPostHas10Comments()
2927
{
30-
factory(BlogPost::class)->create([
31-
'user_id' => $this->user()->id
32-
])->each(function (BlogPost $post) {
28+
$this->blogPost()->each(function (BlogPost $post) {
3329
$post->comments()->saveMany(
3430
factory(Comment::class, 10)->make([
3531
'user_id' => $this->user()->id
@@ -45,7 +41,7 @@ public function testBlogPostHas10Comments()
4541
'data' => [
4642
'*' => [
4743
'id',
48-
'contnt',
44+
'content',
4945
'created_at',
5046
'updated_at',
5147
'user' => [
@@ -60,4 +56,43 @@ public function testBlogPostHas10Comments()
6056
)
6157
->assertJsonCount(10, 'data');
6258
}
59+
60+
public function testAddingCommentsWhenNotAuthenticated()
61+
{
62+
$this->blogPost();
63+
64+
$response = $this->json('POST', 'api/v1/posts/3/comments', [
65+
'content' => 'Hello'
66+
]);
67+
68+
$response->assertStatus(401);
69+
}
70+
71+
public function testAddingCommentsWhenAuthenicated()
72+
{
73+
$this->blogPost();
74+
75+
$response = $this->actingAs($this->user(), 'api')->json('POST', 'api/v1/posts/4/comments', [
76+
'content' => 'Hello'
77+
]);
78+
79+
$response->assertStatus(201);
80+
}
81+
82+
public function testAddingCommentWithInvalidData()
83+
{
84+
$this->blogPost();
85+
86+
$response = $this->actingAs($this->user(), 'api')->json('POST', 'api/v1/posts/5/comments', []);
87+
88+
$response->assertStatus(422)
89+
->assertJson([
90+
"message" => "The given data was invalid.",
91+
"errors" => [
92+
"content" => [
93+
"The content field is required."
94+
]
95+
]
96+
]);
97+
}
6398
}

tests/TestCase.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
66
use App\User;
7+
use App\BlogPost;
78

89
abstract class TestCase extends BaseTestCase
910
{
@@ -13,4 +14,11 @@ protected function user()
1314
{
1415
return factory(User::class)->create();
1516
}
17+
18+
protected function blogPost()
19+
{
20+
return factory(BlogPost::class)->create([
21+
'user_id' => $this->user()->id
22+
]);
23+
}
1624
}

0 commit comments

Comments
 (0)