4

I'm doing a maths contest project using Laravel. All of the controller methods in the project uses a lot of time() functions.

Questions are returned to the user depending on whether the current time is in between the contest live time.

While writing the feature test and unit tests, how do I mimic the time() functions in the controller so as to set my desired time while running tests for the project?

2 Answers 2

19

There is two options that you can do to interact with time:

Option 1: Use Laravel inbuilt function

Note: Laravel Version >= 8

Latest version of Laravel has good method to interact with time:

$this->travel(5)->milliseconds();
$this->travel(5)->seconds();
$this->travel(5)->minutes();
$this->travel(5)->hours();
$this->travel(5)->days();
$this->travel(5)->weeks();
$this->travel(5)->years();

// Travel into the past...
$this->travel(-5)->hours();

// Travel to an explicit time...
$this->travelTo(now()->subHours(6));

// Return back to the present time...
$this->travelBack();

Ref: https://laravel.com/docs/mocking#interacting-with-time

Option 2: Carbon method

Carbon::setTestNow();

Or set any dates

$knownDate = Carbon::create(2001, 5, 21, 12);
Carbon::setTestNow($knownDate); // Or any dates    
echo Carbon::now();  // will show 2001-05-21 12:00:00

Ref: https://laraveldaily.com/carbon-trick-set-now-time-to-whatever-you-want/

Sign up to request clarification or add additional context in comments.

1 Comment

Does the Carbon method actually work? I implement it and I'm not longer able to log into my application; it keeps expiring the login.
1

I think Carbon should be used instead of time():

Carbon::now()->timestamp // Or just now()->timestamp in 5.5+

You can easily mock Carbon instances.

If you don't use time() a lot, you could also create your own helper:

function timestamp()
{
    if (app()->runningUnitTests()) {
        return ....
    } else {
        return time();
    }
}

And use it instead of time():

timestamp()

1 Comment

How about third party packages? I need to create a JWT token and the Firebase package is using \time() instead of Carbon. Really annoying when you have no control.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.