bencarter78@hotmail.com's avatar

Phpspec test fails when using app() helper function

Hi all

I'm a relative newbie when it comes to testing and phpspec but I'm having a problem in one of my tests using the app() helper function.

Call to a member function make() on null in /vendor/laravel/framework/src/Illuminate/Foundation/helpers.php

My test class is...

class PlanUserAssessmentsSpec extends ObjectBehavior
{
    function let(User $user, Sector $sector)
    {
        $this->beConstructedWith($user, $sector);
    }
    
    function it_returns_an_array_of_generated_assessments_for_a_user(User $user)
    {
        $this->handle()->shouldBeArray();
    }

And my class is...

class PlanUserAssessments extends Job implements SelfHandling, ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

    protected $user;

    protected $sector;

    public function __construct(User $user, Sector $sector)
    {
        $this->user   = $user;
        $this->sector = $sector;
    }

    public function handle()
    {
        $userRepo = app(UserRepository::class);

        return [$userRepo->getRoles()];
}

If I run the class in production I get back exactly what I expect, the app function works it's just when I run my test.

Can anyone help me understand why I'm getting the error?

Thanks

0 likes
3 replies
Corez64's avatar
Corez64
Best Answer
Level 37

You can just inject your UserRepository into the handler like so:

public function handle(UserRepository $userRepo)
{
    return [$userRepo->getRoles()];
}

Laravel will automatically inject the class when it calls the handle function just like it does on Controller methods.

kajetons's avatar

That's because the PHPSpec runs in isolation - app() helper requires the Laravel to be bootstrapped to work. There's a package for Laravel: https://github.com/BenConstable/phpspec-laravel.

One thing to note though is that PHPSpec is the most useful when testing domain layer. Using app() and other Laravel helpers inside of it should be avoided in favor of proper DI since you probably don't want to tightly couple your application to a specific framework.

Please or to participate in this conversation.