A
A
Artem00712018-07-09 10:25:19
Laravel
Artem0071, 2018-07-09 10:25:19

What is wrong with testing?

I want to check if a role is "common_user"attached when creating a user. I
created an Observer, in which I add a role when creating a user (everything is normally added to the database, and outputs true):

class UserObserver
{
    /**
     * Handle to the user "created" event.
     *
     * @param  \App\User  $user
     * @return void
     */
    public function created(User $user)
    {
        $role = Role::where('name', 'common_user')->first();

        $user->attachRole($role);

//        dd($user->hasRole('common_user')); // здесь пишит true, то есть у пользователя роль добавилась
    }

But in the test itself:
public function test_created_user_has_user_role()
    {
        $email = $this->faker->email;

        $this->postJson(
            route('user.create'),
            [
                'email' => $email,
                'password' => $this->faker->password,
                'name' => $this->faker->name
            ]
        );

        $user = User::where('email', $email)->first();

        $this->assertNotNull(1, $user); // пользователь создан, (так же в Oberver'e true на присоединенной роли)

//        dd(Role::all()); // здесь просто проверил добавились ли роли (ДА, добавились)
//        $user->fresh(['roles']); // здесь пытался обновить модель, но не вышло

//        dd($user->roles); // здесь выводит Null, не понимаю почему

//        $testUser = User::where('email', $email)->first(); // попробовал получить новую модель

//        dd($testUser->roles); // почему то тоже отсутствуют роли...

        $this->assertTrue($user->hasRole('common_user')); // соответственно тут срабатывает ошибка, тк false
    }

That is, it turns out that the roles were created, joined the user, but still some kind of error ..

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2018-07-09
@alexey-m-ukolov

$user->load(['roles']);

$user->fresh(['roles']); // tried to update the model here, but failed
The fresh method returns a new object rather than modifying the current one.
dd($user->roles); // outputs Null here, I don't understand why
This is really strange - lazy loading should have happened. Show how your user class looks like.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question