fastsol
151
1
Testing

request()->path() incorrect during testing

Posted 1 month ago by fastsol

I am having a hard time figuring out a way to set the pathInfo within the request when testing. Here is the scenario: I am adding a global scope to a model in the boot() of that model that is conditional based on the route that given. This works great under normal usage but testing it fails the condition because the pathInfo within the request is only "/".

What I don't understand is that AFTER the response is returned from the $this->get() in the test, the request has all the correct data, but it is NOT populated beforehand at the route model binding level. It is populated by the time it hits the middleware, but that is too late to attach or not attach a global scope for a route model binding situation.

The page in question is protected behind auth middleware, so the $this->fakeUser(); is simply a quick function to be() a user;

Here is the model code:

public static function boot(){
        parent::boot();

        if(!request()->is('admin/*')){
            static::addGlobalScope(new IsActiveScope());
            dd(request()->path());
        }
    }

As you can see the code is just checking if the route is "admin/*", so any admin pages essentially. But not matter what I have tried, the route always comes through as "/" when it hits that piece of code and the route model binding level. If you do a dd(request()); AFTER the $response in the test, the route has been populated at that point and is correct. This is the test:

/** @test */
    public function see_correct_active_icons_for_each_brand()
    {
        $this->fakeUser();

        $brand1 = factory(Brand::class)->create(['name' => 'A', 'active' => true]);
        $brand2 = factory(Brand::class)->create(['name' => 'B', 'active' => false]);
        $brand3 = factory(Brand::class)->create(['name' => 'C', 'active' => true]);

        $response = $this->get(route('admin.brands.index'));
        
        $response->assertSeeInOrder([$brand1->displayStatus(),$brand2->displayStatus(), $brand3->displayStatus()]);
    }

How can I fake this or is there another way to add the global scope in the manner that works like I have it now?

Please sign in or create an account to participate in this conversation.