4

$this->assertDatabaseHas()不适用于JSON/JSONb列。

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

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

就像是

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

不是一个选项,因为我有一个包含元数据的广泛 JSON。

如何一次检查JSON数据库?

4

3 回答 3

4

UPD

现在可以这样做


我已经用这个单线解决了它(根据你的模型/字段调整它)

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

于 2018-05-06T18:55:22.693 回答
4

拉拉维尔 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,
    ]);
}
于 2020-06-06T16:31:26.340 回答
0

使用json_encode对我有用的值:

$this->assertDatabaseHas('users', [
    'name' => 'Gaurav',
    'attributes' => json_encode([
        'gender' => 'Male',
        'nationality' => 'Indian',
    ]),
]);
于 2021-07-26T06:56:05.580 回答