Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Auto Testify Laravel Package

hidayetov/auto-testify

Laravel package that generates CRUD and uniqueness tests for Eloquent models via an Artisan command. Detects unique fields from the DB schema with doctrine/dbal or from a $unique model property, and skips DB-dependent checks when no connection is available.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the package:

    composer require hidayetov/auto-testify
    

    Optionally install doctrine/dbal for database schema detection:

    composer require doctrine/dbal
    
  2. Publish the config (optional):

    php artisan vendor:publish --provider="Hidayetov\AutoTestify\AutoTestifyServiceProvider" --tag="config"
    

    (Modify config/autotestify.php if needed for custom paths or behavior.)

  3. Run the generator:

    php artisan autotestify:generate ModelName
    

    Example:

    php artisan autotestify:generate User
    
  4. Locate generated tests: By default, tests are created in tests/Feature/Models/{ModelName}Test.php. Verify the output matches your expectations (CRUD + uniqueness tests).


First Use Case

Scenario: You have a User model with fields email (unique) and name. Generate tests to:

  • Validate CRUD operations (create, read, update, delete).
  • Ensure uniqueness constraints (e.g., duplicate email fails).

Command:

php artisan autotestify:generate User

Expected Output:

  • A test file with methods like:
    • test_can_create_user()
    • test_can_retrieve_user()
    • test_can_update_user()
    • test_can_delete_user()
    • test_email_must_be_unique()

Implementation Patterns

Workflows

  1. Integrate into CI/CD:

    • Run autotestify:generate in a pre-test hook to auto-generate tests before running phpunit.
    • Example .github/workflows/test.yml snippet:
      - name: Generate Tests
        run: php artisan autotestify:generate --all
      - name: Run Tests
        run: phpunit
      
  2. Model-Specific Customization:

    • Override generated tests by manually editing the output file.
    • Use traits or base test classes for shared assertions (e.g., TestBase with helper methods).
  3. Partial Generation:

    • Generate tests for specific models only:
      php artisan autotestify:generate User Post
      
    • Skip models with --skip:
      php artisan autotestify:generate --skip=Admin
      
  4. Database-Agnostic Development:

    • Work without a database by defining $unique in your model:
      class User extends Model {
          protected $unique = ['email', 'username'];
      }
      

Integration Tips

  1. Leverage Laravel’s Test Helpers:

    • Use create(), factory(), or refreshDatabase() in generated tests for consistency.
    • Example: Replace hardcoded data with factories:
      // Generated test (may need manual tweaks)
      public function test_can_create_user() {
          $user = User::factory()->create();
          $this->assertDatabaseHas('users', ['id' => $user->id]);
      }
      
  2. Extend Test Coverage:

    • Add custom assertions post-generation:
      // In UserTest.php
      public function test_custom_validation() {
          $response = $this->post('/users', ['email' => 'invalid']);
          $response->assertSessionHasErrors('email');
      }
      
  3. Seed Test Data:

    • Use DatabaseMigrations or DatabaseTransactions traits to ensure clean state:
      use DatabaseMigrations;
      
      class UserTest extends TestCase {
          use DatabaseMigrations;
          // ...
      }
      
  4. Combine with Pest:

    • If using Pest, regenerate tests with php artisan autotestify:generate --pest to adapt syntax:
      // Pest-style output
      it('creates a user', function () {
          $user = User::factory()->create();
          expect($user)->toBeValid();
      });
      

Gotchas and Tips

Pitfalls

  1. Database Connection Issues:

    • Symptom: Tests fail with SQLSTATE[HY000] [2002] (no DB connection).
    • Fix: Ensure .env has valid DB credentials or run tests with --env=testing.
    • Workaround: Use --no-database flag to skip DB-dependent tests:
      php artisan autotestify:generate --no-database
      
  2. Schema Mismatch:

    • Symptom: Unique fields detected via doctrine/dbal don’t match $unique in the model.
    • Fix: Explicitly define $unique in the model to override schema detection:
      protected $unique = ['email']; // Overrides DB schema
      
  3. Test File Overwrites:

    • Symptom: Regenerating tests overwrites manual changes.
    • Fix: Use --append to add tests without replacing:
      php artisan autotestify:generate --append
      
    • Alternative: Generate to a custom directory:
      // config/autotestify.php
      'path' => 'tests/Generated',
      
  4. Foreign Key Constraints:

    • Symptom: Tests fail due to missing related models (e.g., Post requires User).
    • Fix: Generate tests in dependency order or mock relationships:
      // In PostTest.php
      public function setUp(): void {
          parent::setUp();
          $this->user = User::factory()->create();
      }
      

Debugging

  1. Verbose Output:

    • Enable debug mode to see generation steps:
      php artisan autotestify:generate --verbose
      
  2. Check Generated Code:

    • Inspect the output file for errors (e.g., syntax, logic).
    • Example: Search for TODO comments in generated tests.
  3. Validate Unique Fields:

    • Verify $unique in the model or DB schema matches expectations:
      php artisan schema:dump --printer
      

Extension Points

  1. Custom Test Templates:

    • Override the default template by publishing and modifying:
      php artisan vendor:publish --provider="Hidayetov\AutoTestify\AutoTestifyServiceProvider" --tag="views"
      
    • Edit resources/views/autotestify/test.blade.php.
  2. Add Custom Test Methods:

    • Extend the generator by creating a custom command:
      // app/Console/Commands/GenerateCustomTests.php
      use Hidayetov\AutoTestify\Generators\TestGenerator;
      
      class GenerateCustomTests extends Command {
          protected $signature = 'autotestify:custom {model}';
          public function handle() {
              $generator = new TestGenerator();
              $generator->addCustomMethod('test_custom_logic');
              $generator->generate($this->argument('model'));
          }
      }
      
  3. Hook into Generation:

    • Use the autotestify.generated event to post-process tests:
      // app/Providers/EventServiceProvider.php
      protected $listen = [
          'autotestify.generated' => [
              'App\Listeners\PostProcessTest',
          ],
      ];
      
  4. Skip Specific Tests:

    • Exclude certain test types via config:
      // config/autotestify.php
      'skip_tests' => ['uniqueness'], // Skip uniqueness tests
      

Pro Tips

  • Pair with laravel-shift/database-resetter: Reset the DB between test runs to avoid state pollution.
  • Use --dry-run: Preview changes without writing files:
    php artisan autotestify:generate --dry-run
    
  • Template Partial Generation: Generate only CRUD or uniqueness tests:
    php artisan autotestify:generate --only=crud User
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
gmostafa/php-graphql-client
xeviant/paystack
snowsoft/faker
meditationsteps/blogetc
animalyoung/laravel-influxdb
onix-solutions/sms-telera
lonely-lights/prosetta
oxygen/data
oxygen/core
jengo/base
xiloryx/log-collector
a21ns1g4ts/filament-stripe
la-php/laravel-admin
artisan-build/community-prompts
vleroy/smart
ayles-software/laravel-australian-public-holidays
cboxdk/laravel-id-spatie
cboxdk/laravel-id-billing
cboxdk/laravel-id-billing-bridge
simple-as-fuck/php-performance-log