phpspec/phpspec — pull request #433 by Warbo (2014-08-15 14:33:23+00:00)
Title: Allow examples to return failures

This change allows examples to indicate failure in the simplest and most natural way: via their return value. It seems that the return values of examples are currently being ignored, so that custom invariants can only be checked via a Rube Goldberg mechanism of interacting side-effects. For example:

class FormControllerSpec extends ObjectBehaviour
{
// let, etc. goes here
function it_generates_urls()
{
$this->getUrl('arg1', 'arg2', 'arg3')->shouldBeAUrl();
}
function getMatchers()
{
return ['beAUrl' => function($string) {
return filter_var($string, FILTER_VALIDATE_URL) === $string;
}];
}
}

This might be useful for often-used logic (although using an array of functions seems to be [reinventing PHP's object system](http://en.wikipedia.org/wiki/Inner-platform_effect)). For one-off logic it breaks [locality](http://codeblab.com/2009/12/code-locality/) and requires an [extra layer of abstraction](http://c2.com/cgi/wiki?TooMuchAbstraction).

With this change, examples can indicate failure by returning an error message (in fact, any truthy value). Existing examples won't fail, since they return NULL, which is falsy. The above example becomes:

class FormControllerSpec extends ObjectBehaviour
{
// let, etc. goes here
function it_generates_urls()
{
$string = $this->getUrl('arg1', 'arg2', 'arg3')->getWrappedObject();
if (filter_var($string, FILTER_VALIDATE_URL) === false) return "Expected a URL, given '$string'";
}
}