#development #laravel #php #testing
During testing with the Laravel framework, you often want to check if a database contains a record which contains a JSON string (especially if you are using JSON columns in your database).
You might have found that using json_encode
doesn't work:
1$this->assertDatabaseHas(
2 'backups',
3 [
4 'tries' => 1,
5 'status' => BackupStatus::SUCCESS,
6 'message' => null,
7 'document_id' => $document->id,
8 'destinations' => json_encode(['a', 'b']),
9 ]
10);
Due to a difference in the way the JSON string is encoded, the check will fail (.
To fix it, you simply need to use $this->castAsJson
instead (API documentation can be found here:
1$this->assertDatabaseHas(
2 'backups',
3 [
4 'tries' => 1,
5 'status' => BackupStatus::SUCCESS,
6 'message' => null,
7 'document_id' => $document->id,
8 'destinations' => $this->castAsJson(['a', 'b']),
9 ]
10);
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.