Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I unit test an Eloquent model record being inserted in Laravel 5?

Everything I've googled for relating to this suggests that you shouldn't unit test Eloquent as it's already unit tested within Laravel.

However in this case I have another class, that is not an Eloquent model, but it does insert an Eloquent model record into the database. I want to unit test this class.

For example:

public function methodIWantToTest()
{
    $record = new User();

    $user->name = 'Bob';
    $user->email = '[email protected]';

    $user->save();
}

How would I unit test this method? When I try it actually inserts into the database. Surely I should be able to do this without even having to go near the database?

like image 711
Gnuffo1 Avatar asked Sep 05 '16 16:09

Gnuffo1


People also ask

What is refreshDatabase in Laravel?

refreshDatabase() Define hooks to migrate the database before and after each test. bool. usingInMemoryDatabase() Determine if an in-memory database is being used.

What is PHPUnit Laravel?

Use Laravel Unit Testing to Avoid Project-Wrecking Mistakes. Pardeep Kumar. 7 Min Read. PHPUnit is one of the most well known and highly optimized unit testing packages of PHP. It is a top choice of many developers for rectifying different developmental loopholes of the application.


1 Answers

if you don't want to use seeInDatabase() maybe you should try:

$mock = Mockery::mock('User');
$mock->shouldReceive('save')->once()->andReturn(true); 
$this->assertTrue(methodIWantToTest($mock));
like image 63
Sherif Avatar answered Sep 23 '22 20:09

Sherif