Skip to content

Instantly share code, notes, and snippets.

@ninthspace
Last active April 15, 2021 17:19
Show Gist options
  • Save ninthspace/9b33e812ed581c25ec353afcdf4dea5c to your computer and use it in GitHub Desktop.
Save ninthspace/9b33e812ed581c25ec353afcdf4dea5c to your computer and use it in GitHub Desktop.
Time travel with Dusk without pesky JavaScript
<?php
// update Controller.php as follows
namespace App\Http\Controllers;
use App\Services\TimeTravel;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
public function __construct()
{
$this->middleware(function ($request, $next) {
TimeTravel::check();
return $next($request);
});
}
}
// and in your Dusk tests
public function tearDown(): void
{
TimeTravel::stop();
}
// and for each test that needs to time travel
public function testSomething()
{
TimeTravel::to('2021-01-23');
$this->browse(function (Browser $browser) {
// etc
}
}
<?php
namespace App\Services;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
class TimeTravel
{
const KEY = 'time-travel.test-date';
public static function to(string $dateTimeString)
{
if (! self::isPermitted()) {
return;
}
Cache::set(self::KEY, $dateTimeString);
}
public static function stop()
{
if (! self::isPermitted()) {
return;
}
Cache::forget(self::KEY);
Carbon::setTestNow();
}
public static function check()
{
if (! self::isPermitted()) {
return;
}
if (Cache::has(self::KEY)) {
Carbon::setTestNow(Carbon::parse(Cache::get(self::KEY)));
}
}
public static function isPermitted()
{
return config('app.env') === 'testing';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment