Last active
October 21, 2016 14:25
-
-
Save scottgrayson/61ca73ca096632d8ea44f538b7ad3f16 to your computer and use it in GitHub Desktop.
API testing with json() and seeJson()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use App\User; | |
use App\Profile; | |
use Illuminate\Foundation\Testing\WithoutMiddleware; | |
use Illuminate\Foundation\Testing\DatabaseMigrations; | |
use Illuminate\Foundation\Testing\DatabaseTransactions; | |
class UpdateUserTest extends TestCase | |
{ | |
use DatabaseMigrations, WithoutMiddleware; | |
/** | |
* A basic functional test example. | |
* | |
* @return void | |
*/ | |
public function testUpdatingUser() | |
{ | |
$user = factory(User::class)->create(['username' => 'my-username']); | |
$profile = factory(Profile::class)->make(['bio' => 'my-bio']); | |
$user->profile()->save($profile); | |
$this->be($user); | |
$this->json('PUT', '/api/users/'.$user->uuid, [ | |
'bio' => 'new-bio', | |
'username' => 'new-username' | |
])->seeJson([ | |
'success' => true | |
]); | |
$this->visit('/api/users/'.$user->uuid) | |
->see('new-bio') | |
->see('new-username'); | |
} | |
} |
rewrote it and the ->assertResponseOk() method is giving me better errors if i purposely put one in the controller
<?php
use App\User;
use App\Profile;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class UserRestTest extends TestCase
{
use DatabaseMigrations, WithoutMiddleware;
/**
* A basic functional test example.
*
* @return void
*/
public function testUpdatingUser()
{
$user = factory(User::class)->create(['username' => 'my-username']);
$profile = factory(Profile::class)->make(['bio' => 'my-bio']);
$user->profile()->save($profile);
$this->be($user);
$this->put('/api/users/'.$user->uuid, [
'bio' => 'new-bio',
'username' => 'new-username'
])->assertResponseOk();
$this->get('/api/users/'.$user->uuid)
->seeJson([
'bio' => 'new-bio',
'username' => 'new-username'
]);
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It took me a while to get this test to pass, because i was getting "invalid argument supplied to foreach()" from phpunit output.
All the deeper errors (model, controller, etc. related) were being suppressed. I found them in the logs.
How would you write this so that phpunit can give me a better idea of what is wrong? Any other tips? This is my second test after writing the first one while following your video.