Answer the question
In order to leave comments, you need to log in
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, то есть у пользователя роль добавилась
}
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
}
Answer the question
In order to leave comments, you need to log in
$user->load(['roles']);
$user->fresh(['roles']); // tried to update the model here, but failedThe fresh method returns a new object rather than modifying the current one.
dd($user->roles); // outputs Null here, I don't understand whyThis 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 questionAsk a Question
731 491 924 answers to any question