You can follow the simple steps below.


Install


composer require --dev phpspec/phpspec:2.2.1

Dummy class to test


# football/src/Application/FrontendBundle/Service/CountryService.php
namespace Application\FrontendBundle\Service;

use Application\FrontendBundle\Exception\CountryException;
use Application\FrontendBundle\Repository\CountryRepository;
use Doctrine\DBAL\DBALException;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\ORMException;
use Exception;

class CountryService implements CountryServiceInterface
{
private $entityManager;
private $countryRepository;

public function __construct(
EntityManager $entityManager,
CountryRepository $countryRepository
) {
$this->entityManager = $entityManager;
$this->countryRepository = $countryRepository;
}

public function getList()
{
try {
return $this->countryRepository->findAll();
} catch (DBALException $e) {
$message = sprintf('DBALException: %s', $e->getMessage());
} catch (ORMException $e) {
$message = sprintf('ORMException: %s', $e->getMessage());
} catch (Exception $e) {
$message = sprintf('Exception: %s', $e->getMessage());
}

throw new CountryException($message);
}
}

Create test class


# football/src/Application/FrontendBundle/Service/CountryService.php
Inanzzz-MBP:football inanzzz$ bin/phpspec describe Application/FrontendBundle/Service/CountryService
Specification for Application\FrontendBundle\Service\CountryService created in /Library/WebServer/Documents/football/spec/Application/FrontendBundle/Service/CountryServiceSpec.php.

Running the test


# Run single test
Inanzzz-MBP:football inanzzz$ bin/phpspec run spec/Application/FrontendBundle/Service/CountryServiceSpec.php

# Run all tests
Inanzzz-MBP:football inanzzz$ bin/phpspec run

Write the test


# football/spec/Application/FrontendBundle/Service/CountryServiceSpec.php
namespace spec\Application\FrontendBundle\Service;

use Application\FrontendBundle\Entity\Country;
use Application\FrontendBundle\Repository\CountryRepository;
use Doctrine\ORM\EntityManager;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class CountryServiceSpec extends ObjectBehavior
{
function it_is_initializable()
{
$this->shouldHaveType('Application\FrontendBundle\Service\CountryService');
}

function let(
EntityManager $entityManager,
CountryRepository $countryRepository
) {
$this->beConstructedWith($entityManager, $countryRepository);
}

function it_should_return_country_instance(
CountryRepository $countryRepository,
Country $country
) {
$countryRepository->findAll()->willReturn($country);

$this->getList()->shouldReturn($country);
}
}

Run the test


Inanzzz-MBP:football inanzzz$ bin/phpspec run spec/Application/FrontendBundle/Service/CountryServiceSpec.php
100% 2
1 specs
2 examples (2 passed)
122ms