Test Your Trait With PHP Spec
Testing your trait with PHP Spec could seem like a tough job, at least, that's what it looked like to me. Since a spec
represents the class you're testing and a trait can't be instantiated, it might seem not possible. Thankfully PHP Spec is amazing. I've only been using it for a full week now and I've never had more fun testing. The object and method creation is amazing. Ok. That's enough. Now let's talk about the solution to test your trait.
It's actually fairly simple.
The answer to the question "How can I test my trait?"is.. use a stub. Create a stub that uses the trait. In my case I wanted to test the trait EventRecorder
and generated a spec for this trait by running
bin/phpspec describe Project/Namespace/EventRecorder
Remove the included it_is_initializable
method in the spec. Now to be able to call a method on the trait with $this, the spec should be an instance of
the trait. Alright, time for some code examples.
<?php namespace Project\Namespace;
trait EventRecorder
{
}
<?php namespace Project\Namespace\Stubs;
use Project\Namespace\EventRecorder;
class EventRecorderStub
{
use EventRecorder;
}
And now the spec
<?php
namespace spec\Project\Namespace;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class EventRecorderSpec extends ObjectBehavior
{
function let()
{
$this->beAnInstanceOf('Project\Namespace\Stubs\EventRecorderStub');
}
}
Now the spec uses the stub and thus the trait. The only downside I could find was that the method creation didn't work right, but now you are able to successfully test the trait.
Founder of Kooding. Event Sourcerer at heart.