API test helpers
This repository makes it easier for you to test REST APIs.
We've added a couple of integration testing helpers that you're to use.
test helper | Usage |
---|---|
seeApiSuccess() | Asserts response returned using success response macro:return response()->success(..) |
seeValidationError() | Asserts response code is 422 and that the error is returned (you get that when Laravel throws a validation error or when you return response()->error('message', 422); |
seeApiError($status_code) | Asserts for specific status code error.. for example 401. |
seeJsonKey($key) | equivalent to ->see('"'.$key.'"'): |
seeJsonValue($value) | equivalent to ->see('"'.$value.'"') |
seeJsonArray($entity) | equivalent to ->see('"'.$entity.'":[') Which is useful when you expect an array of Orders for example. |
seeJsonObject($entity) | equivalent to ->see('"'.$entity.'":{') Which is useful when you expect a single Order for example. |
Avoid using bcrypt() in your model factory. As it'll slow down your tests. Only use it if you want to know the password of the user model created (e.g.: in login, reset password tests).
Here's an example controller and integration test for it
<?php
$api->group([], function ($api) {
$api->post('posts', 'PostsController@create');
});
<?php
use App\Post;
class PostsController{
public function create(Request $request)
{
$this->validate($request, [
'name' => 'required',
]);
$post = Post::create([
'name' => $request->input('name'),
]);
return response()->success(compact('post'));
}
}
<?php
class CreatePostTest extends TestCase
{
public function testCreatingNewPostSuccessfully()
{
$post = factory(App\Post::class)->make();//we're not saving it in the database
$this->post('/api/posts', ['name' => $post->name])
->seeApiSuccess()
->seeJsonObject('post')
->seeJson(['name' => $post->name]);
$this->seeInDatabase('posts', [
'name' => $post->name,
]);
}
}
Don't forget the
/api/
at the beginning of the route in your test file.
Updated less than a minute ago