Laravel: Factories created with boolean values in column fails to pass test case with assertDatabaseHas in mysql database

Viewed 2467

The Question

I have my table sample with columns has_value and has_condition which are boolean type created by laravel in MySQL. In Factory of the sample table I have set the faker value to be boolean. In test case I have passed the faker value as it is. The laravel stores the value properly but the test case with assertDatabaseHas fails as MySQL stores the values in numeric value but the faker is providing the boolean value.

The setup

Migration

Schema::create('sample', function (Blueprint $table) {
   $table->unsignedBigInteger();
   $table->boolean('has_value')->default(false);
   $table->boolean('has_condition')->default(false);
});

Model

class Sample extends Model {
  
   /**
     * The attributes that aren't mass assignable.
     *
     * @var array
     */
    protected $guarded = ['id', 'created_at', 'updated_at'];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'has_condition' => 'boolean',
        'has_value' => 'boolean',
    ];
}

The factory

$factory->define(Sample::class, function (Faker $faker) {
    return [
        'has_condition' => $faker->boolean,
        'has_value' => $faker->boolean
    ];
});

The test case

use DatabaseMigrations;

public function test_is_being_stored()
{
  $data = factory(Sample::class)->make()->toArray();
  $user = factory(User::class)->create()
  $this->actingAs($user)->post(route('some.route.store'), $data)
    ->assertSessionHasNoErrors()
    ->assertStatus(200);

  $this->assertDatabaseHas('sample', $data)
}

The result is as follows

Failed asserting that a row in the table [campaign_tax_years] matches the attributes {
    "has_condition": true,
    "has_value": true
}.

Found: [
    {
        "id": 27,
        "created_at": "2020-07-01 07:36:52",
        "updated_at": "2020-07-01 07:36:52",
        "has_condition": 1,
        "has_value": 1
    }
]

The value check in the database are not typecasted checks. But the value being stored is correct. I am unable to understand why Laravel is not casting the values and then checking for column types.

Various Item Versions

Laravel: 6.8.x Mysql: 5.7.29 Phpunit: ^8.0

0 Answers
Related