Search code examples
rspecphpunitbddphpspec

PHP spec - array of specific types


In phpspec how would a spec look that tested that a class property contained an array of specific types?

for example:

class MyClass
{
   private $_mySpecialTypes = array();

   // Constructor ommitted which sets the mySpecialTypes value

   public function getMySpecialTypes()
   {
      return $this->_mySpecialTypes;
   }
}

My spec looks like this:

public function it_should_have_an_array_of_myspecialtypes()
{
    $this->getMySpecialTypes()->shouldBeArray();
}

But i want to make sure that each element in the array is of type MySpecialType

Whats the best way to do this in phpspec?


Solution

  • You can use an inline matcher:

    namespace spec;
    
    use PhpSpec\ObjectBehavior;
    use Prophecy\Argument;
    
    use MySpecialType;
    
    class MyArraySpec extends ObjectBehavior
    {
        function it_should_have_an_array_of_myspecialtypes()
        {
            $this->getMySpecialTypes()->shouldReturnArrayOfSpecialTypes();
        }
    
        function getMatchers()
        {
            return array(
                'returnArrayOfSpecialTypes' => function($mySpecialTypes) {
                    foreach ($mySpecialTypes as $element) {
                        if (!$element instanceof MySpecialType) {
                            return false;
                        }
                    }
                    return true;
                }
            );
        }
    }