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

ZejdCicak's avatar

Testing a model that has some JSON fields

I am writing a test for creating a record in database in table that has 3 json fields, and the thing is when I try to create it it goes smoothly but assertDatabaseHas returns some strange errors even after using castAsJson:

SQLSTATE[42883]: Undefined function: 7 ERROR: operator does not exist: json = json

How did you manage to test these kind of models? I can provide more information if needed.

0 likes
8 replies
ZejdCicak's avatar

@SilenceBringer

/** @test */
    public function can_store_faculty(): void{
        $data = $this->validFormData();
        $this->post(uri: route('administration.faculties.store'), data: $data);

        $this->assertDatabaseHas('faculties', [...$data,
            'letter_grades' => $this->castAsJson($data['letter_grades']),
            'description_grades' => $this->castAsJson($data['description_grades']),
            'final_subject_ids' => $this->castAsJson($data['final_subject_ids'])
        ]);
    }

My test looks like this, it is pretty basic but these JSON fields seem to be an issue, and I do need them so I can't rid of them.

The model that I'm testing looks like this

 protected $fillable = [
        'name', 'short_name', 'summary', 'registration_number', 'dean', 'phone', 'fax', 'email', 'website', 'logo', 'status', 'institution_id', 'days_before_locking',
        'first_cycle_type', 'min_class_percentage', 'min_test_percentage', 'min_homework_percentage', 'show_test_registration', 'description_grades', 'letter_grades',
        'name_en', 'final_subject_ids', 'practice_subject_id', 'referent_name_first_cycle', 'referent_name_second_cycle', 'referent_name_third_cycle'
    ];

    protected $dates = ['deleted_at'];

    protected $casts = [
        'letter_grades' => 'array',
        'description_grades' => 'array',
        'final_subject_ids' => 'array'
    ];

So everything is pretty simple at the moment, but this model gives me trouble.

tisuchi's avatar

@zejdcicak You can use assertDatabaseHas.

For example-

Model::where('rules->required', null)->get();

In the test,

/** @test */
public method a_model_can_be_stored
{
    // Do some stuff...
 
    $this->assertDatabaseHas('models', [
        'rules->required' => null,
    ]);
}
Tray2's avatar

First you need to ask yourself why the hell you store something as json. After that you need to extract those fields into tables and columns. When that is done you will have no more issues.

Oh and you should read this

https://tray2.se/posts/database-design

ZejdCicak's avatar

@Tray2 That is not a solution to my problem, I do need json since its not a list of foreign keys.

Please or to participate in this conversation.