Let's say I have this class that I was spec-ing (following BDD approach)
class Logger
{
private $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public function logMessageAsRead(Message $message)
{
$log = new LoggedMessage($message);
$this->em->persist($message);
}
}
and LoggedMessage
is defined as follows
class LoggedMessage
{
private $date;
private $message;
public function __construct(Message $message)
{
$this->date = new \DateTime();
$this->message = $message;
}
}
Sometimes my spec example fails due to discrepancy from Message
date instantiated in spec and the one in the Logger
class.
class LoggerSpec
{
public function it_logs_a_message(Message $message, EntityManager $em)
{
$log = new LoggedMessage($message);
$em->persist($log)->shouldBeCalled(1);
$this->logMessageAsRead($message);
}
}
Question number one: Do I have a smell in my code, so do I need to create a collaborator (ie.: a factory) and inject it into Logger
in order to create a new LoggedMessage
?
Question number two: If is not necessary to inject a new collaborator, how can I be sure that my spec works every single time and not fail in a random fashion due to date time discrepancy?