Summer Sale! All accounts are 50% off this week.

peterdickins's avatar

Ignore seconds in Timestamp comparison

I have a few tests that are occasionally failing because the timestamp is out by 1 second.

/** @test */
public function a_user_can_update_a_product()
{
    $product = Product::factory()->create();

    $attributes = $product->toArray();
    $attributes['name'] = 'Changed';

    $this->post(route('product.edit', [
            'item' => $product->id
        ]), $attributes);

    $this->get(route('product.edit', [
            'item' => $product->id
        ]))->assertOk();

    $this->assertDatabaseHas('products', $attributes);
}

Here is the result:

1) Tests\Feature\ProductsTest::a_user_can_update_a_product
Failed asserting that a row in the table [products] matches the attributes {
    "title": "Changed",
    "updated_at": "2022-02-10 12:11:31",
    "created_at": "2022-02-10 12:11:31",
    "id": 1
}.

Found similar results: [
    {
        "id": "1",
        "title": "Changed",
        "created_at": "2022-02-10 12:11:31",
        "updated_at": "2022-02-10 12:11:32",
        "deleted_at": null
    }
].

Is there a way that seconds can be ignored in the timestamp comparison?

0 likes
2 replies
tykus's avatar

I don't like your test. The premise is incorrect because your real form data will not include id, created_at, updated_at or deleted_at; but, your test request does include them. I also don't know what the get request proves (in the context of editing a Product)?

In my opinion, this would be a better test of functionality you are trying to prove - and more succinct too:

/** @test */
public function a_user_can_update_a_product()
{
    $product = Product::factory()->create();

    $this->post(route('product.edit', $product->id), ['name' => 'Changed']);

    $this->assertDatabaseHas('products', ['id' => $product->id, 'name' => 'Changed']);
}
2 likes
Pati's avatar

I agree to @tykus.

Your test implicitly includes a "the updated_at timestamp should not update when a product is updated" condition, which is most likely not want you want :)

Please or to participate in this conversation.