Testing Dates In Laravel
Aug 27, 2017 · 2 min read
Imagine we have a website that shows a list of upcoming films.
The list may comprise of a title and release date.
<div>
<h2 class=”title”>{!! $film->title !!}</h2>
<p>{!! $film->release_date->format(‘l, F jS, Y’) !!}</p>
</div>
Pirates of the Caribbean
Sunday, May 25th, 2017
To test that our website shows a list of films, we can set up a test file. Our file might look something like:
<?phpnamespace Tests\Feature;use Carbon\Carbon;
use Tests\TestCase;
use App\Eloquent\Film;
use Illuminate\Foundation\Testing\{
DatabaseMigrations, DatabaseTransactions
};class ViewFilmsTest extends TestCase
{
use DatabaseMigrations,
DatabaseTransactions;
/** @test */
public function we_can_view_a_list_of_upcoming_films()
{
factory(Film::class)->create([
'title' => 'Pirates of the Caribbean',
'release_date' => Carbon::parse('2017-05-25 00:00')
]);
$response = $this->get('/');
$response->assertStatus(200);
$response->assertSee('Pirates of the Caribbean');
$response->assertSee('Sunday, May 25th, 2017');
}
}
When we run our tests…
OK (1 test, 3 assertions)Great, but what’s the problem?
When making small changes to the release dates format (Sunday May 28th, 2017) we’re going to get unwanted failures in our test suite.
FAILURES!
Tests: 1, Assertions: 3, Failures: 1.Tests failing over aesthetics isn’t ideal. We would like to avoid these false positives as much as possible.
So, what’s the solution?
https://developer.mozilla.org/en/docs/Web/HTML/Element/time
<time datetime=”{!! $film->release_date->format(‘Y-m-d H:i’) !!}”>
{!! $film->release_date->format(‘l F jS, Y’) !!}
</time>
Adjust our test suite:
<?phpnamespace Tests\Feature;use Carbon\Carbon;
use Tests\TestCase;
use App\Eloquent\Film;
use Illuminate\Foundation\Testing\{
DatabaseMigrations, DatabaseTransactions
};class ViewFilmsTest extends TestCase
{
use DatabaseMigrations,
DatabaseTransactions;
/** @test */
public function we_can_view_a_list_of_upcoming_films()
{
factory(Film::class)->create([
'title' => 'Pirates of the Caribbean',
'release_date' => Carbon::parse('2017-05-25 00:00')
]);
$response = $this->get('/');
$response->assertStatus(200);
$response->assertSee('Pirates of the Caribbean');
$response->assertSee('2017-05-25 00:00');
}
}
Re-run our tests and Voilà :) We can now change the format of our date without breaking our test suite.
OK (1 test, 3 assertions)