Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i properly test Laravel events?

I'm writing tests for a model which fires an event when one of its properties is changed. Unfortunately, I can't figure out the best way to test this. The model code is:

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 the event fire:

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

The problem is, the above tests still pass if:

  • no event occurred at all
  • I'm changing the model's name for a second time (which, should fire the event for a second time, right?)

How can i make my tests pass only if one foo.NameChange event occurred? All other senario's should fail my test.

like image 274
nstapelbroek Avatar asked Nov 01 '22 08:11

nstapelbroek


1 Answers

You have to call Mockery::close() in your tearDown() method. See the Mockery docs on PHPUnit integration.

like image 129
Bram Gerritsen Avatar answered Nov 08 '22 05:11

Bram Gerritsen