Summer Sale! All accounts are 50% off this week.

luddinus's avatar

Ugly or genius? (Pest and Actions)

Hi,

I am using actions (simple classes with an execute method that only do "one thing"). I started using Pest and I'm thinking to have the execute method and a test method in the same class (in the action class)

class CreateUser
{
    public function execute(array $attributes)
   {
      $user = User::create($attributes);
      // ...
     return $user;
   }

   public static function test()
   {
      app(self::class)->execute(['name' => 'Toure Yaya']);

      expect(User::count())->toBe(1);
      // more assertions
   }
}

and from the pest classes, a helper like this

test(CreateUser::class, function () {
   CreateUser::test();
});

What do you think?

0 likes
3 replies
Tray2's avatar

No.

A test should reside in it's own test class and not in the CreateUser class.

It could look something like this (phpunit)

class AuthorTest extends TestCase
{
    /**
    * @test
    */
    public function name_property_returns_the_authors_last_name_and_first_name()
    {
        $author = Author::factory()->make([
            'first_name' => 'Robert',
            'last_name' => 'Jordan'
        ]);

        $this->assertEquals('Jordan, Robert', $author->name);
    }
}
class Author extends Model
{
    use HasFactory;

    protected $guarded = [];

    public function getNameAttribute()
    {
        return $this->last_name . ', ' . $this->first_name;
    }
}
luddinus's avatar

@Tray2 I know that a test "should" have it owns class, but looking Pest, it seems like we have more "freedom" to where to define our tests...

Tray2's avatar

@luddinus No we don't, since we don't want test code in production. And how do we know which code is test and which is production. My advise is keep them separated.

1 like

Please or to participate in this conversation.