Hello, I have a problem when testing command to create a user. The flow is using Artisan command to create user and test if the record exists. However, the record count is 0 instead of 1. I think it may be caused by the sequence of code running. How can I get rid of it?
Here is the code.
$command->expectsOutput(__('command.system.initiate.first-user'))
->expectsQuestion(__('command.system.create-user.username'), $name)
->expectsQuestion(__('command.system.create-user.email'), $email)
->expectsQuestion(__('command.system.create-user.password'), 'password')
->expectsOutput(__('command.system.create-user.information', ['name' => $name, 'email' => $email]))
->expectsConfirmation(__('command.system.create-user.confirm'), 'yes')
->expectsOutput(__('command.system.create-user.success'))
->assertSuccessful();
$this->assertDatabaseCount(\App\Models\User::class, 1);
$this->assertDatabaseHas(\App\Models\User::class, ['name' => $name]);
public function handle()
{
$name = $this->ask(__('command.system.create-user.username'));
$email = $this->ask(__('command.system.create-user.email'));
$password = $this->secret(__('command.system.create-user.password'));
$this->info(__('command.system.create-user.information', ['name' => $name, 'email' => $email]));
if ($this->confirm(__('command.system.create-user.confirm'))) {
try {
DB::beginTransaction();
$user = User::create([
'name' => $name,
'email' => $email,
'password' => Hash::make($password),
]);
DB::commit();
return self::SUCCESS;
} catch (\Throwable $e) {
DB::rollBack();
$this->error(__('command.system.create-user.failure', ['error' => $e->getMessage()]));
return self::FAILURE;
}
}
}
And the test result is failed with no result inserted, although it can be dumped after create.
Failed asserting that table [users] matches expected entries count of 1. Entries found: 0.