From 45d3e0a0c175ab85072e4d24f086386c38c6e342 Mon Sep 17 00:00:00 2001 From: Italo Date: Mon, 14 Mar 2022 15:34:58 -0300 Subject: [PATCH] [9.x] Adds "freezeTime" helper for tests. (#41460) * [9.x] Adds "freezeTime" helper for tests. * Removes start of second. Returns callback result, if any. * Adds freezeCurrentSecond for DB timestamps without subsecond precision. * formatting Co-authored-by: Taylor Otwell --- .../Testing/Concerns/InteractsWithTime.php | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/src/Illuminate/Foundation/Testing/Concerns/InteractsWithTime.php b/src/Illuminate/Foundation/Testing/Concerns/InteractsWithTime.php index bacbce882168..0dd044664156 100644 --- a/src/Illuminate/Foundation/Testing/Concerns/InteractsWithTime.php +++ b/src/Illuminate/Foundation/Testing/Concerns/InteractsWithTime.php @@ -7,6 +7,28 @@ trait InteractsWithTime { + /** + * Freeze time. + * + * @param callable|null $callback + * @return mixed + */ + public function freezeTime($callback = null) + { + return $this->travelTo(Carbon::now(), $callback); + } + + /** + * Freeze time at the beginning of the current second. + * + * @param callable|null $callback + * @return mixed + */ + public function freezeSecond($callback = null) + { + return $this->travelTo(Carbon::now()->startOfSecond(), $callback); + } + /** * Begin travelling to another time. * @@ -30,7 +52,7 @@ public function travelTo($date, $callback = null) Carbon::setTestNow($date); if ($callback) { - return tap($callback(), function () { + return tap($callback(Carbon::now()), function () { Carbon::setTestNow(); }); }