I
I
Ilya Loopashko2021-04-23 11:57:11
Laravel
Ilya Loopashko, 2021-04-23 11:57:11

What is the correct way to create a unit test for a pivot table?

Good afternoon. I want to create a test for a controller. There are three tables, roles, categories and categories_roles, a many-to-many relationship.

Controller

/**
     * Update connections.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function update(Request $request) {

        $input = $request->get('category', []);
        foreach (Category::all() as $category) {
            $category->roles()->sync(Arr::get($input, $category->id, []));
        }
        return view('home');
    }


I can’t figure out how to write a test, I have an idea in my head, but I don’t know how to implement it. As I started to do so far.

unit test
/** @test */
    public function test_admin_user_can_edit_categories_roles()
    {
        $this->actingAs(\App\Models\User::factory()->create(['role_id' => 1]));
        $input = [
            "1" => [
                "1" => "1"
            ],
            "2" => [
                "1" => "1"
            ],
        ];
        $this->post('/admin/connections', $input);
    }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question