【问题标题】:PHPUnit assertDatabaseHas with Laravel and InertiaPHPUnit assertDatabaseHas 与 Laravel 和 Inertia
【发布时间】:2021-03-23 19:50:29
【问题描述】:

我有一个使用 Intertia.js 的 Laravel 8 设置。我正在尝试使用 assertDatabaseHas() 方法测试我的发布路线以存储新资源并希望断言数据库已存储新记录。

Controller.php

public function store(SlotCreate $request): RedirectResponse
    {
        $slot = CreateSlot::dispatchNow($request);

        return redirect()->back()->with([
            'message' => 'Slot Created Successfully.',
            'slot' => new SlotResource($slot)
        ]);
    }

CreateSlotTest.php

public function testCreateSlot()
    {
        $response = $this->actingAs($this->teamAdminOne)->post('/slots', [
            'start_time' => '09:00',
            'end_time' => '10:00',
            'max_bookings' => 3
        ]);

        $response->assertStatus(302);

        $this->assertDatabaseHas('slots', [
            'id' => ???
            'team_id' => $this->teamAdminOne->currentTeam(),
            'start_time' => '09:00',
            'end_time' => '10:00',
            'max_bookings' => 3
        ]);
    }

当我调试会话时,我可以看到我添加到 with() 方法的插槽,但我不知道如何访问它。

我想知道我是否在控制器中正确返回了插槽,如果是,我如何访问响应以断言数据库是否有此记录?

【问题讨论】:

  • 您可以通过以下方式访问会话中的变量:Illuminate\Support\Facades\Session::get('slot')
  • @TohidDadashnezhad 完美。您可以添加为答案,我会接受。出于兴趣,这是从 Inertia 中的控制器返回数据的正确方法吗?
  • 很高兴能为您提供帮助。老实说,我从来没有体验过 Inertia,就个人而言,我总是更喜欢将后端和前端代码分开,并为每个单独的项目。

标签: php laravel phpunit inertiajs


【解决方案1】:

实际上当你调用redirect()->with()时,它通过调用session()->flush()方法将变量添加到会话中。所以在这种情况下,您可以通过Illuminate\Support\Facades\Session 外观检索变量。

$slot = Illuminate\Support\Facades\Session::get('slot')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-13
    • 2017-09-15
    • 2021-06-25
    • 2018-10-29
    • 2021-01-09
    • 2019-08-12
    • 2021-05-04
    • 2021-05-30
    相关资源
    最近更新 更多