Skip to content
brianium edited this page Nov 8, 2014 · 2 revisions

Similar to Mocha's use of shared behaviors, Peridot can accomplish testing similar objects with a simple PHP require statement.

Consider a User object that is extended by an Admin object. Instead of duplicating test code for whether or not both of these objects behave like a user, we can create a specification to share between them:

shared/behaves-like-user.php:

it('should have a first name', function() {
    $firstName = $this->user->getFirstName();
    assert($firstName == "brian", "first name should be brian");
});

it('should have a last name', function() {
    $lastName = $this->user->getLastName();
    assert($lastName == "scaturro", "last name should be scaturro");
});

describe('getFullName()', function() {
    it('should return the full name', function() {
        $full = $this->user->getFullName();
        assert($full == "brian scaturro", "full name should be brian scaturro");
    });
});

user.spec.php:

use Peridot\Example\User;

describe('User', function() {
    beforeEach(function() {
        $this->user = new User("brian", "scaturro");
    });

    require 'shared/behaves-like-user.php';
});

admin.spec.php:

use Peridot\Example\Admin;

describe('Admin', function() {
    beforeEach(function() {
        $this->user = new Admin("brian", "scaturro");
    });

    require 'shared/behaves-like-user.php';

    it('should be an admin', function() {
        assert($this->user->isAdmin(), "should be admin");
    });
});

User.php:

namespace Peridot\Example;

class User 
{
    /**
     * @var string
     */
    protected $first;

    /**
     * @var string
     */
    protected $last;

    /**
     * @param $first
     * @param $last
     */
    public function __construct($first, $last)
    {
        $this->first = $first;
        $this->last = $last;
    }

    /**
     * @return string
     */
    public function getFirstName()
    {
        return $this->first;
    }

    /**
     * @param string $first
     */
    public function setFirstName($first)
    {
        $this->first = $first;
        return $this;
    }

    /**
     * @return string
     */
    public function getLastName()
    {
        return $this->last;
    }

    /**
     * @param string $last
     */
    public function setLastName($last)
    {
        $this->last = $last;
        return $this;
    }

    /**
     * @return string
     */
    public function getFullName()
    {
        return sprintf("%s %s", $this->getFirstName(), $this->getLastName());
    }
}

Admin.php:

namespace Peridot\Example;

class Admin extends User
{
    /**
     * @return bool
     */
    public function isAdmin()
    {
        return true;
    }
}
Clone this wiki locally