4

I'm (we're) creating a package that acts as a core component for our future CMS and of course that package needs some unit tests. When the package registeres, the first thing it does is set the back/frontend context like this:

class FoundationServiceProvider extends ServiceProvider
{
    // ... stuff ...

    public function register()
    {
        // Switch the context.
        // Url's containing '/admin' will get the backend context
        // all other urls will get the frontend context.
        $this->app['build.context'] = request()->segment(1) === 'admin'
                ? Context::BACKEND
                : Context::FRONTEND;
    }
}

So when I visit the /admin url, the app('build.context') variable will be set to backend otherwise it will be set to `frontend.

To test this I've created the following test:

class ServiceProviderTest extends \TestCase
{

    public function test_that_we_get_the_backend_context()
     {
        $this->visit('admin');
        $this->assertEquals(Context::BACKEND, app('build.context'));
    }
}

When I'm running the code in the browser (navigating to /admin) the context will get picked up and calling app('build.context') will return backend, but when running this test, I always get 'frontend'.

Is there something I did not notice or some incorrect code while using phpunit?

Thanks in advance

frietkot
  • 891
  • 12
  • 28

1 Answers1

4

Well, this is a tricky situation. As I understand it, laravel initiates two instances of the framework when running tests - one that is running the tests and another that is being manipulated through instructions. You can see it in tests/TestCase.php file.

So in your case you are manipulating one instance, but checking the context of another (the one that did not visit /admin and is just running the tests). I don't know if there's a way to access the manipulated instance directly - there's nothing helpful in documentation on this issue.

One workaround would be to create a route just for testing purposes, something like /admin/test_context, which would output the current context, and the check it with

$this->visit('admin/test_context')->see(Context::BACKEND);

Not too elegant, but that should work. Otherwise, look around in laravel, maybe you will find some undocumented feature.

Tadas Paplauskas
  • 1,863
  • 11
  • 15