Subscribed unsubscribe Subscribe Subscribe

Kentaro Kuribayashi's blog

Software Engineering, Management, Books, and Daily Journal.

Idea: PSpec (WIP)

I hacked up some code, sort of RSpec-like. It can be used like below:

<?php
namespace PSpec;
require_once "PSpec.php";

describe("PSpec describe()", function () {
    echo "I have just implemented only describe()";
});

PSpec.php:

<?php
namespace PSpec;

class World
{
    public static $data = [];

    public function shutdown()
    {
        foreach (self::$data as $description => $example_group) {
            $example_group->call();
        }
    }
}

$world = new World();
register_shutdown_function(array($world, 'shutdown'));

class ExampleGroup
{
    public $callback;

    public function __construct(callable $callback)
    {
        $this->callback = $callback;
    }

    public function call()
    {
        call_user_func($this->callback);
    }
}

function describe($description, callable $callback)
{
    $example_group = new ExampleGroup($callback);
    World::$data[$description] = $example_group;
}

The core of this implementation is to use register_shutdown_function to invoke all the examples without explicite method calling. How do you think of it?