Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

gallib's avatar

Testing an expiration date with PHPUnit

Hi,

I'm adding a new feature on a package. Goal is to have an expires_at column on a url table. I'm trying to write some tests for that but I have no idea on how to test that.

More precisely, How can I insert a valid url (with a valid expires_at in the future), and right after try to call this url and get something like "This url is no longer valid".

I could try something like:

/** @test */
public function an_url_could_expire()
{
        $url = $this->createUrl(['code' => 'abcde', 'expires_at' => Carbon::now()->add('PT10M')]);

    $response = $this->get($url);

    $this->assertArrayHasKey('code', $response['errors']);
}

But I've no idea on how to tweak the response of $this->get, I don't remember seeing anything similar on laracasts.

Thanks for your help!

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

You can modify the current time in the test context using the Carbon::setTestNow() method:

/** @test */
public function an_url_could_expire()
{
    $url = $this->createUrl([
        'code' => 'abcde',
        'expires_at' => Carbon::now()->add('PT10M')
    ]);

    Carbon::setTestNow(now()->addMinutes(11); // 1 minute after expiry

    $response = $this->get($url);

    $this->assertArrayHasKey('code', $response['errors']);
}
gallib's avatar

Wow, I didn't know this method, I will try that this evening and let you know, thanks!

Edit: it works like a charm, thanls!

Please or to participate in this conversation.