Last active
February 19, 2020 23:47
-
-
Save wemakewaves/5831247 to your computer and use it in GitHub Desktop.
Making assertions on an instance of DatePeriod with PHPSpec
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
... | |
class DeliveryDateService extends ObjectBehavior | |
{ | |
... | |
function it_should_return_all_sundays_up_to_the_last_available_delivery_date_when_today_is_a_sunday() | |
{ | |
//Set the first date in the range to be Sunday, 23rd of June 2013 (16:00) | |
$firstDate = new \DateTime(); | |
$firstDate->setDate(2013, 6, 23); | |
$firstDate->setTime(16, 0); | |
$this->setFirstDate($firstDate); | |
//Set the last date in the range to be 3 months after the first date | |
$lastDate = clone $firstDate; | |
$lastDate->add(new \DateInterval('P3M')); | |
$this->setLastDate($lastDate); | |
$dateRange = $this->getSundaysWithinDateRange(); | |
$dateRange->shouldBeAnInstanceOf('DatePeriod'); | |
//Unwrap the DatePeriod object so that we can traverse and count | |
$unwrappedDateRange = $dateRange->getWrappedSubject(); | |
foreach ($unwrappedDateRange as $date) { | |
if ($date->format('l') != 'Sunday') { | |
throw new \Exception(sprintf('Expected "Sunday" but actually got "%s"', $date->format('l'))); | |
} | |
if ($date->getTimestamp() > $lastDate->getTimestamp()) { | |
throw new \Exception(sprintf('A timestamp of a date in the DatePeriod is larger than the last available date: %s(%d) > %s(%d)', $date->format('d/m/Y'), $date->getTimestamp(), $lastDate->format('d/m/Y'), $lastDate->getTimestamp())); | |
} | |
if ($date->getTimestamp() < $firstDate->getTimestamp()) { | |
throw new \Exception(sprintf('A timestamp of a date in the DatePeriod is smaller than the first available date: %s(%d) < %s(%d)', $date->format('d/m/Y'), $date->getTimestamp(), $lastDate->format('d/m/Y'), $lastDate->getTimestamp())); | |
} | |
} | |
if (count(iterator_to_array($unwrappedDateRange)) !== 14) { | |
throw new \Exception(sprintf('Expected 14 Sundays, but got %d', count(iterator_to_array($unwrappedDateRange)))); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment