lorisleiva / laravel-actions

⚡️ Laravel components that take care of one specific task
https://laravelactions.com
MIT License
2.41k stars 117 forks source link

Feature Test + Artisan Call from asCommand Not Respecting DatabaseTransactions #272

Open WorthLMS opened 5 months ago

WorthLMS commented 5 months ago

PHPUnit Testing

use DatabaseTransactions;

# Record is Removed from Database After this Test
public function test_asObject_CreateUserAction()
{
    CreateUserAction::run([
        'first_name' => 'Test', 
        'last_name' => 'Test'
    ]);

    $this->assertDatabaseCount('users', 1);
}

# Record Remains in the Database After This Test
public function test_asCommand_CreateUserAction()
{
  $this->artisan('create:user', [
      'first_name' => 'Test',
      'last_name' => 'Test',
  ]);

 $this->assertDatabaseCount('users', 1);
}

class CreateUserAction
{
    use WithAttributes, AsObject, AsCommand, AsFake;

    public string $commandSignature = 'create:user
        {first_name : First Name}
        {last_name : First Name}
    ';

    public string $commandDescription = 'Creates a New User in the System';
    public string $commandHelp = '';
    public bool $commandHidden = false;

    public function getValidationAttributes(): array
    {
        return [
            'first_name' => 'First Name',
            'last_name' => 'Last Name',
        ];
    }

    public function rules(): array
    {
        return [
            'first_name' => [ 'required', 'string', 'max:25' ],
            'last_name' => [ 'required', 'string', 'max:25' ],
        ];
    }

    public function asCommand(CommandAlias $command): int
    {
            $this->handle([
                'first_name' => $command->argument('first_name'),
                'last_name' => $command->argument('last_name'),
            ]);

            return Command::SUCCESS;
    }

    public function handle(array $attributes = []): Model|User
    {
        $this->fill($attributes);

        $validated = $this->validateAttributes();

        # Create User
        return User::create($validated);
    }