Last active
April 15, 2021 17:19
-
-
Save ninthspace/9b33e812ed581c25ec353afcdf4dea5c to your computer and use it in GitHub Desktop.
Time travel with Dusk without pesky JavaScript
This file contains 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 | |
// 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); | |
}); | |
} | |
} |
This file contains 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
// 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 | |
} | |
} |
This file contains 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 | |
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