Skip to content

Use Carbon::now() for fresh timestamps so that Carbon's time mocking works #1870

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jan 17, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/Jenssegers/Mongodb/Eloquent/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ public function getDateFormat()
*/
public function freshTimestamp()
{
return new UTCDateTime(time() * 1000);
return new UTCDateTime(Carbon::now());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this be:

Suggested change
return new UTCDateTime(Carbon::now());
return new UTCDateTime(Carbon::now()->getTimestamp() * 1000);

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like UTCDateTime also supports DateTime interfaces 👌

}

/**
Expand Down
10 changes: 10 additions & 0 deletions tests/ModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,16 @@ public function testDates(): void
$this->assertEquals((string) $user->getAttribute('entry.date')->format('Y-m-d H:i:s'), $data['entry']['date']);
}

public function testCarbonDateMockingWorks()
{
$fakeDate = \Carbon\Carbon::createFromDate(2000, 01, 01);

Carbon::setTestNow($fakeDate);
$item = Item::create(['name' => 'sword']);

$this->assertLessThan(1, $fakeDate->diffInSeconds($item->created_at));
}

public function testIdAttribute(): void
{
/** @var User $user */
Expand Down