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

Internal Test Helpers Laravel Package

symfonycasts/internal-test-helpers

Internal test utilities from SymfonyCasts to streamline PHPUnit and Symfony/Laravel package testing. Provides shared helpers, fixtures, and assertions used across SymfonyCasts projects to reduce boilerplate and keep tests consistent and readable.

Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer:

    composer require --dev symfonycasts/internal-test-helpers
    

    No additional configuration is required.

  2. First Use Case Use the TestHelper trait in your test classes to generate realistic test data:

    use Symfonycasts\InternalTestHelpers\TestHelper;
    
    class UserTest extends TestCase
    {
        use TestHelper;
    
        public function test_create_user_with_fake_data()
        {
            $user = User::factory()->create([
                'email' => $this->faker->unique()->safeEmail,
                'password' => 'password123',
            ]);
    
            $this->assertDatabaseHas('users', [
                'email' => $user->email,
            ]);
        }
    }
    
  3. Where to Look First

    • Faker Integration: Explore $this->faker for generating fake data (e.g., emails, names, addresses).
    • Database Helpers: Check $this->createModel() and $this->createModels() for quick model creation.
    • Assertions: Use $this->assertDatabaseHas() or $this->assertDatabaseMissing() for database checks.

Implementation Patterns

Usage Patterns

  1. Generating Fake Data Leverage Faker for realistic test data:

    $user = User::factory()->create([
        'name' => $this->faker->name,
        'email' => $this->faker->unique()->email,
    ]);
    
  2. Model Creation Use createModel() for one-off model creation or createModels() for bulk creation:

    $post = $this->createModel(Post::class, ['title' => 'Test Post']);
    $posts = $this->createModels(Post::class, 5); // Creates 5 posts
    
  3. Database Assertions Verify database state without querying:

    $this->assertDatabaseHas('posts', ['title' => 'Test Post']);
    $this->assertDatabaseMissing('posts', ['title' => 'Deleted Post']);
    
  4. Testing API Endpoints Combine with Laravel's HTTP tests:

    $response = $this->postJson('/api/users', [
        'email' => $this->faker->unique()->email,
        'password' => 'password123',
    ]);
    $this->assertDatabaseHas('users', ['email' => $response['email']]);
    
  5. Seeding Relationships Create nested relationships easily:

    $user = $this->createModel(User::class);
    $posts = $this->createModels(Post::class, 3, ['user_id' => $user->id]);
    

Workflows

  • Test Data Setup: Use setUp() to seed test data once per test class.
  • Cleanup: Laravel's transactions (via refreshDatabase()) handle rollbacks, but manually delete test data if needed:
    public function tearDown(): void
    {
        User::where('email', 'like', '%@test.com')->delete();
        parent::tearDown();
    }
    

Integration Tips

  • Pair with Laravel Factories: Extend factories for domain-specific logic:
    $user = User::factory()->create([
        'role' => $this->faker->randomElement(['admin', 'editor', 'user']),
    ]);
    
  • Customize Faker: Override Faker providers for domain-specific data:
    $this->faker->addProvider(new CustomFakerProvider($this->faker));
    
  • Mock External Services: Use Faker to generate realistic mock responses.

Gotchas and Tips

Pitfalls

  1. Faker State Persistence

    • Faker maintains state between calls (e.g., unique emails). Reset it if tests interfere:
      $this->faker->seed(1234); // Reset seed for reproducibility
      
    • Avoid $this->faker->unique() in loops without resetting seeds.
  2. Database Assertions vs. Queries

    • assertDatabaseHas() is slower than direct queries. Use it for critical checks only.
    • False negatives may occur if the database isn’t fully synced (e.g., during transactions).
  3. Model Creation Quirks

    • createModel() uses create(), not factory(). Ensure your models support both.
    • Mass assignment risks: Always validate input or use fill() + save() for safety:
      $post = new Post();
      $post->fill(['title' => $this->faker->sentence])->save();
      
  4. Testing Observers/Events

    • Observers may trigger during createModel(). Disable them in tests if needed:
      User::observe();
      User::observe(NoOpObserver::class); // Replace with a no-op observer
      

Debugging

  • Faker Output: Dump Faker’s last generated value:
    dd($this->faker->format('The email is %email%'));
    
  • Database State: Inspect the database directly:
    $this->assertDatabaseCount('posts', 1);
    
  • Slow Tests: Profile database assertions with:
    $this->withoutExceptionHandling(); // Temporarily disable exceptions
    

Config Quirks

  • No Configuration: The package is zero-config. All helpers are traits/methods.
  • Faker Customization: Extend the default Faker instance in setUp():
    public function setUp(): void
    {
        parent::setUp();
        $this->faker->addProvider(new AppFakerProvider($this->faker));
    }
    

Extension Points

  1. Custom Helpers Extend the trait or create your own:

    trait CustomTestHelper
    {
        protected function createAdminUser(): User
        {
            return $this->createModel(User::class, [
                'email' => $this->faker->unique()->email,
                'role' => 'admin',
            ]);
        }
    }
    
  2. Faker Providers Add domain-specific providers:

    $this->faker->addProvider(new class($this->faker) extends FakerProvider {
        public function paymentMethod(): string
        {
            return $this->faker->randomElement(['credit_card', 'paypal', 'bank_transfer']);
        }
    });
    
  3. Assertion Macros Extend Laravel’s assertions:

    use Illuminate\Testing\Assertions;
    
    Assertions::macro('seeUserInDatabase', function ($email) {
        $this->assertDatabaseHas('users', ['email' => $email]);
    });
    
  4. Test Data Factories Combine with Laravel’s factories for complex setups:

    $user = User::factory()->create();
    Post::factory()->count(5)->create(['user_id' => $user->id]);
    
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.
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk