Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      Sunshine And March Vibes (2025 Wallpapers Edition)

      May 18, 2025

      The Case For Minimal WordPress Setups: A Contrarian View On Theme Frameworks

      May 18, 2025

      How To Fix Largest Contentful Paint Issues With Subpart Analysis

      May 18, 2025

      How To Prevent WordPress SQL Injection Attacks

      May 18, 2025

      Gears of War: Reloaded — Release date, price, and everything you need to know

      May 18, 2025

      I’ve been using the Logitech MX Master 3S’ gaming-influenced alternative, and it could be your next mouse

      May 18, 2025

      Your Android devices are getting several upgrades for free – including a big one for Auto

      May 18, 2025

      You may qualify for Apple’s $95 million Siri settlement – how to file a claim today

      May 18, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      YTConverter™ lets you download YouTube videos/audio cleanly via terminal — especially great for Termux users.

      May 18, 2025
      Recent

      YTConverter™ lets you download YouTube videos/audio cleanly via terminal — especially great for Termux users.

      May 18, 2025

      NodeSource N|Solid Runtime Release – May 2025: Performance, Stability & the Final Update for v18

      May 17, 2025

      Big Changes at Meteor Software: Our Next Chapter

      May 17, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Gears of War: Reloaded — Release date, price, and everything you need to know

      May 18, 2025
      Recent

      Gears of War: Reloaded — Release date, price, and everything you need to know

      May 18, 2025

      I’ve been using the Logitech MX Master 3S’ gaming-influenced alternative, and it could be your next mouse

      May 18, 2025

      How to Make Your Linux Terminal Talk Using espeak-ng

      May 18, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Using Eloquent Factories With PHPUnit Data Providers

    Using Eloquent Factories With PHPUnit Data Providers

    June 4, 2024

    There are a few ways to work with Laravel’s factories in feature tests, such as creating a model during setUp() when you want to use it for multiple tests or directly in an individual test case. If you have a test case that you want to test against a variety of data, you might want to reach for PHPUnit’s data providers with Eloquent models.

    Using data providers with feature tests can pose a problem because they run before Laravel is bootstrapped via the framework’s TestCase that runs during setUp(). Data providers are resolved early in the process of running phpunit, so you’ll run into the following error if you want to use them:

    <?php

    namespace TestsFeature;

    use AppModelsUser;
    use IlluminateFoundationTestingRefreshDatabase;
    use PHPUnitFrameworkAttributesDataProvider;
    use TestsTestCase;

    class ExampleTest extends TestCase
    {
    use RefreshDatabase;

    #[DataProvider(‘nonAdminUsers’)]
    public function test_non_admin_users_cannot_access_admin($user): void
    {
    $response = $this
    ->actingAs($user())
    ->get(‘/admin’)
    ->assertStatus(403);
    }

    public static function nonAdminUsers(): array
    {
    return [
    [User::factory()->player()->create()],
    [User::factory()->coach()->create()],
    [User::factory()->owner()->create()],
    ];
    }
    }

    If you run the above test, you should get something like the following error, depending on which version of Laravel you are using—the following is what I get on Laravel 11:

    $ vendor/bin/phpunit tests/Feature/ExampleTest.php

    There was 1 PHPUnit error:

    1) TestsFeatureExampleTest::test_non_admin_users_cannot_access_admin
    The data provider specified for TestsFeatureExampleTest::test_non_admin_users_cannot_access_admin is invalid
    A facade root has not been set.

    tests/Feature/ExampleTest.php:18

    This is because when the data provider code runs, the Laravel app hasn’t been bootstrapped! If you’re a Pest PHP user, the Bound Datasets example illustrates using a closure for model data:

    it(‘can generate the full name of a user’, function (User $user) {
    expect($user->full_name)->toBe(“{$user->first_name} {$user->last_name}”);
    })->with([
    fn() => User::factory()->create([‘first_name’ => ‘Nuno’, ‘last_name’ => ‘Maduro’]),
    fn() => User::factory()->create([‘first_name’ => ‘Luke’, ‘last_name’ => ‘Downing’]),
    fn() => User::factory()->create([‘first_name’ => ‘Freek’, ‘last_name’ => ‘Van Der Herten’]),
    ]);

    In PHPUnit, we could use closures to pass code to our test via data providers without immediately trying to create the data:

    namespace TestsFeature;

    use AppModelsUser;
    use IlluminateFoundationTestingRefreshDatabase;
    use PHPUnitFrameworkAttributesDataProvider;
    use TestsTestCase;

    class ExampleTest extends TestCase
    {
    use RefreshDatabase;

    #[DataProvider(‘nonAdminUsers’)]
    public function test_non_admin_users_cannot_access_admin($user): void
    {
    $response = $this
    ->actingAs($user())
    ->get(‘/admin’)
    ->assertStatus(403);
    }

    public static function nonAdminUsers(): array
    {
    return [
    [fn(): User => User::factory()->player()->create()],
    [fn(): User => User::factory()->coach()->create()],
    [fn(): User => User::factory()->owner()->create()],
    ];
    }
    }

    Note the $user() call, which we pass to actingAs(). If you need to use the model in various places, just assign it to a variable. Now, factory data is created in the test, which is precisely what we want! To learn more about HTTP feature tests in Laravel, check out the documentation.

    The post Using Eloquent Factories With PHPUnit Data Providers appeared first on Laravel News.

    Join the Laravel Newsletter to get all the latest Laravel articles like this directly in your inbox.

    Source: Read More 

    Hostinger
    Facebook Twitter Reddit Email Copy Link
    Previous ArticleJeremy’s Larabits: How to Provision a Server with Laravel Forge
    Next Article Data & Dragons: Perficient Attends Data + AI Summit

    Related Posts

    Development

    February 2025 Baseline monthly digest

    May 18, 2025
    Artificial Intelligence

    Markus Buehler receives 2025 Washington Award

    May 18, 2025
    Leave A Reply Cancel Reply

    Continue Reading

    IBM and Hugging Face Researchers Release SmolDocling: A 256M Open-Source Vision Language Model for Complete Document OCR

    Machine Learning

    A Fresh Design for a Better Flowbite Experience

    Web Development

    A New Minimal Default Exception Page With Dark Mode Support in Laravel 11.9

    Development

    Philippines Cyber Revolution Summit 2024: Charting the Future of Cybersecurity

    Development
    GetResponse

    Highlights

    Development

    How to Test Microphone on Ubuntu?

    June 13, 2024

    You have a microphone input connected to your Ubuntu system. But, before you hop on…

    Heatseeker – general-purpose fuzzy selector

    July 7, 2024

    Malicious ML Models on Hugging Face Leverage Broken Pickle Format to Evade Detection

    February 8, 2025

    CVE-2025-4466 – iSourcecode Gym Management System SQL Injection Vulnerability

    May 9, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.