How to prevent model events from firing with phpunit?

I want to prevent model events like "created". "updated", etc. when testing my application using phpunit.

The Laravel documentation says that you can prevent events from firing with

$this->expectsEvents(App\Events\UserRegistered::class);

But in my situation, I have nothing to expect.

Even if I use $this->withoutEvents(); to prevent all events, eloquent events are generated.

How can I prevent eloquent events?

+5
source share
3 answers

A look at the Laravel Api Model::flushEventListeners() should "Delete all event listeners for the model."

EDIT

You can write a user base of methods on this:

 public static function flushEventListeners() { if (! isset(static::$dispatcher)) { return; } $instance = new static; foreach ($instance->getObservableEvents() as $event) { static::$dispatcher->forget("eloquent.{$event}: ".get_called_class()); } } 

Something like this might be:

 public static function flushEventListenersProvided($events) { if (! isset(static::$dispatcher)) { return; } $instance = new static; foreach ($instance->getObservableEvents() as $event) { if(in_array($event, $events)){ static::$dispatcher->forget("eloquent.{$event}: ".get_called_class()); } } } 

and maybe add it as a dash to the models or a basic model that will expand with all of your models. This code has not been tested, but should give you an idea of ​​how this can be done.

+4
source

Check out the shouldReceive method of the Model class. Basically, the Model class extends Mockery . Here is an example assuming you have a Car class:

 Car::shouldReceive('save')->once(); 

This will not get into the database, but will use the layout instead. You can find more information on Laravel testing here: http://laravel.com/docs/4.2/testing

Hope this helps.

+1
source

You should be able to use

 $model = new App\Model($inputs); $this->expectsEvents(['eloquent.creating: App\Model', 'eloquent.saved: App\Model']); $model->save(); 
+1
source

Source: https://habr.com/ru/post/1232353/


All Articles