Are attribute casting tests worth the hassle?

Janez Cergolj • September 2, 2020

Among others, Laravel offers a neat feature where model's attributes are cast to desired cast types. Although I follow the Laravel community regularly, I've never come across an article that would cover this topic. Let's fix this now.

If you don't know what casting is you can check the docs here.

For the purpose of this article let's have a User model with casts property.

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime'
    ];
}

I asked myself a few questions:

I come up with two possible solutions. Both of them are two liners and very basic.

First one

/** @test */
public function assert_email_verified_at_is_cast()
{
    $user = new User();
    $this->assertSame('datetime', $user->getCasts()['email_verified_at']);
}

This unit test is straightforward. We utilize getCasts method that returns all the cast attributes.

Second one

/** @test */
public function assert_email_verified_at_is_cast()
{
    $user = new User(['email_verified_at' => '2001-01-01 00:00:00']);
    $this->assertInstanceOf(Carbon::class, $user->email_verified_at);
}

Here is a second option. Here we check if email_verified_at is cast to Carbon. Those kinds of tests actually test Laravel internal code.

Arguably, both those tests have very little value and might be considered as a spell checker for the code. On the other hand, tests that prevent bugs are a valuable asset to your code. In the end, every dev for himself should decide if it is worth it or not. Now at least you have an option.

p.s. Here is an example of how I do it.