Tim Withers
Tim Withers

Reputation: 12059

Laravel - Unit Testing Model Save

I am working on mocking a save function in Laravel for testing. I have a saving() event that I am trying to test. I have tried using Eloquent::shouldReceive('save') but it gives a fatal error: Fatal error: Cannot instantiate abstract class Illuminate\Database\Eloquent\Model.

This is my test so far:

public function testRemoveAttributesOnSave(){
    Eloquent::shouldReceive('save')->once()->andReturn(true);
    $this->model->attributeA=1;
    $this->model->attributeB=2;
    $this->model->save();
    $this->assertTrue(!isset($this->model->attributeB));
}

What I want to write is self explanatory on the test. I am trying to handle the validation in the model, and protect some attributes from being included after saving.

If I am going about this wrong, please let me know.

Upvotes: 1

Views: 3608

Answers (1)

Tim Withers
Tim Withers

Reputation: 12059

I did a search and found an answer in a comment here on SO

When you use model events (public static function boot()), PHPUnit does not register the events and they go ignored. Now it remains to be answered as to whether this is PHPUnit's fault or Laravel's fault, but hopefully it is something that will be addressed in future releases.

To overcome the issue, you need to manually call the boot() method in your unit test, and you can do it in the setUp():

public function setUp(){
    parent::setUp();
    Artisan::call('migrate');
    $this->seed();
    $this->model=new User;
    User::boot();
}

Hope this helps anyone using Laravel and working on unit testing.

Upvotes: 5

Related Questions