Search code examples
phptddbddphpspec

How to user ThrowException matcher in PHPSpec?


I have problem in using ExceptionMatcher...My example spec:

class DescribeBall extends \PHPSpec\Context {

private $_ball = null;

function before() {
    $this->_ball = $this->spec(new Ball);
}

function itShouldHaveStatusRolledOnRoll() {
        $this->_ball->roll();
        $this->_ball->getStatus()->should->be('Rolled');
}

function itShouldThrowException() {
    $this->_ball->getException()->should->throwException('Exception','Error');
}
}

My example class

class Ball {
    private $status = null;

    public function roll() {
        $this->status = 'Rolled';
    }

    public function getStatus() {
        return $this->status;
    }

    public function getException() {
        throw new Exception('Error');
    }

}

Anyone used this matcher with success?

$this->_ball->getException()->should->throwException('Exception','Error');

Solution

  • Thanks to my colleagues:

    "The last time I looked at it, it used closures (unless Marcello changed it meanwhile) it should still work like this":

    function itShouldThrowException() { 
        $ball = $this->_ball;
        $this->spec(function() use ($ball) {
                $ball->getException();
            })->should->throwException('Exception','Error');
    }