Skip to content

Instantly share code, notes, and snippets.

@tuanpht
Last active March 30, 2020 15:05
Show Gist options
  • Save tuanpht/64003cf9b86a33ff46388a34937d5644 to your computer and use it in GitHub Desktop.
Save tuanpht/64003cf9b86a33ff46388a34937d5644 to your computer and use it in GitHub Desktop.
Laravel Eloquent integration test model save with DB
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Hash;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function hasVerifiedEmail()
{
return !is_null($this->email_verified_at);
}
}
<?php
namespace App\Services\Web;
use App\Models\User;
class UserService
{
public function verifyUser($user)
{
$user->email_verified_at = now();
return $user->save() ? $user : false;
}
}
<?php
namespace Tests\Feature\Service\Web;
use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\Services\Web\UserService;
use App\Models\User;
class UserServiceTest extends TestCase
{
use DatabaseTransactions;
public function testItReturnUserWhenVerifySuccess()
{
$notVerifiedUser = factory(User::class)->create([
'email_verified_at' => null,
]);
$result = (new UserService)->verifyUser($notVerifiedUser);
// Re-get from DB to check it is saved or not
$notVerifiedUser->refresh();
$this->assertTrue($result);
$this->assertTrue($notVerifiedUser->hasVerifiedEmail());
}
public function testItReturnFalseWhenVerifyUserFailed()
{
$notVerifiedUser = factory(User::class)->create([
'email_verified_at' => null,
]);
// Prevent model saving?
User::saving(function () {
return false;
});
$result = (new UserService)->verifyUser($notVerifiedUser);
// Re-get from DB to check it is saved or not
$notVerifiedUser->refresh();
$this->assertFalse($result);
$this->assertFalse($notVerifiedUser->hasVerifiedEmail());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment