Question

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?

Était-ce utile?

La 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;
            }
        );
    }
}

Autres conseils

PHP has no Array of specific types, therefore PHP spec can not test for that directly. You could port the obligatory code over and over and push it into your specs just to control your classes behave like you spec'ed them, or you can create such an array type and spec it.

That would allow you to move the specs to the single object of such a type, spec it once and use it everywhere.

A perhaps well looking base-type is SPLs' SplObjectStorage from your you can extend and make the type a parameter or the first addition the type to accept.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top