How to check Laravel events correctly?

I am writing tests for a model that fires an event when one of its properties changes. Unfortunately, I cannot find a better way to test this. Model Code:

class Foo extends Eloquent { public function setNameAttribute($value) { $this->attributes['name'] = $value; if($this->exists && ($this->original['name'] != $value)) { Event::fire('foo.NameChange', array($this)); } } } 

My initial test for fire events:

 $bar = Foo::first(); Event::shouldReceive('fire')->once()->with('foo.NameChange', array($bar)); $bar->name = 'test'; 

The problem is that the above tests still pass if:

  • Event did not happen at all
  • I change the model name a second time (which should fire the event a second time, right?)

How can I pass my tests only if the foo.NameChange event foo.NameChange ? Everyone else senario should skip my test.

+5
source share
1 answer

You must call Mockery::close() in your tearDown() method. See mockery docs for PHPUnit integration.

+2
source

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


All Articles