lorisleiva / laravel-actions

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

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

Closed WorthLMS closed 1 month ago

WorthLMS commented 8 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);
    }
Wulfheart commented 1 month ago

Would love to see a PR for this.

Wulfheart commented 1 month ago

Ok, honestly, I don't understand the issue if I think about it again. As it is older I am going to close it. If you feel your issue is still relevant please open a new one with a link to a repository containing a minimal reproducible example.