We use PHPSpec for unit testing our Symfony 2 applications. It’s a great tool but occasionally can throw you a curve ball and recently I experienced one such occasion.
I recently discovered PHP’s DatePeriod class which provides a nice way of iterating over a set of dates at regular intervals. Because it implements the Traversable interface we can use a foreach to loop over the interim dates and format them however we need. It worked well however I had some issues using PHPSpec to make assertions on the dates. If I wanted to check the amount of dates in a DatePeriod I would normally convert it to an array using the iterator_to_array() function. However that throws up the following error:
error: Argument 1 passed to iterator_to_array() must implement interface Traversable, instance of</em> <strong><em>PHPSpec2ProphetObjectProphet given…
PHPSpec wraps returned values in this ObjectProphet class which allows you to use their assertions on the results, in addition to making your method calls due to some crafty magic methods. The solution? Simply unwrap the subject from the prophet with the getWrappedSubject() method. We can now make our own assertions on its size and contents: