Laravel 5.6。如何测试JSON / JSONb列

时间:2018-05-06 18:16:15

标签: laravel postgresql jsonb laravel-5.6 laravel-testing

$this->assertDatabaseHas()无法使用JSON / JSONb列。

那么如何在Laravel中测试这些类型的列呢?

目前,我有一个商店行动。如何执行断言,保存了具有预定义值的特定列。

这样的东西

['options->language', 'en']

NOT 一个选项,因为我有一个广泛的带有元素的JSON。

如何一次检查数据库中的JSON

3 个答案:

答案 0 :(得分:4)

Laravel 7 +

不确定该解决方案的作用范围。

我找到了解决方案。忽略一些数据标签,一切都可以访问,我只是在玩弄我的测试来弄清楚它。

/**
 * @test
 */
public function canUpdate()
{
    $authUser = UserFactory::createDefault();
    $this->actingAs($authUser);

    $generator = GeneratorFactory::createDefault();

    $request = [
        'json_field_one' => [
            'array-data',
            ['more-data' => 'cool'],
            'data' => 'some-data',
            'collection' => [
                ['key' => 'value'],
                'data' => 'some-more-data'
            ],
        ],
        'json_field_two' => [],
    ];

    $response = $this->putJson("/api/generators/{$generator->id}", $request);
    $response->assertOk();

    $this->assertDatabaseHas('generators', [
        'id' => $generator->id,
        'generator_set_id' => $generator->generatorSet->id,

        // Testing for json requires arrows for accessing the data
        // For Collection data, you should use numbers to access the indexes
        // Note:  Mysql dose not guarantee array order if i recall. Dont quote me on that but i'm pretty sure i read that somewhere.  But for testing this works
        'json_field_one->0' => 'array-data',
        'json_field_one->1->more-data' => 'cool',

        // to access properties just arrow over to the property name
        'json_field_one->data' => 'some-data',
        'json_field_one->collection->data' => 'some-more-data',

        // Nested Collection
        'json_field_one->collection->0->key' => 'value',

        // Janky way to test for empty array
        // Not really testing for empty
        // only that the 0 index is not set
        'json_field_two->0' => null,
    ]);
}

答案 1 :(得分:0)

我用这个单线程解决了它(根据您的模型/字段进行调整)

$this->assertEquals($store->settings, Store::find($store->id)->settings);

答案 2 :(得分:0)

对值使用 json_encode 对我有用:

$this->assertDatabaseHas('users', [
    'name' => 'Gaurav',
    'attributes' => json_encode([
        'gender' => 'Male',
        'nationality' => 'Indian',
    ]),
]);