简体   繁体   中英

Laravel View::share() does not work when testing

In my Laravel 4 project I've bound the current user to the views using the share() method like so:

View::share(['currentUser' => Sentry::getUser()]);

This works when browsing the site, all the views have access to the variable $currentUser . However, when attempting to test my application, the variable is never bound, despite a user definitely being logged in.

class PagesControllerTest extends TestCase
{
    public function setUp()
    {
        parent::setUp();

        // This works, as halting the application and dumping the user manually demonstrate it as such.
        Sentry::login(User::first());
    }

    public function testIndex()
    {
        $this->get('/');

        $this->assertResponseOk();
    }
}

However, this simply results in a stack-trace of errors...

ErrorException: Trying to get property of non-object (View: ~/Sites/laravel/app/views/layouts/application.blade.php) (View: ~/Sites/laravel/app/views/layouts/application.blade.php)

...

Caused by
ErrorException: Trying to get property of non-object (View: ~/Sites/laravel/app/views/layouts/application.blade.php)

...

Caused by
ErrorException: Trying to get property of non-object

The exact line this fails at is where the view tries to access the $currentUser variable.

If I use a view composer instead, like follows, it solves the problem in this instance - but I want the variable available in ALL views, not just the ones I specify, and I'd also like to know WHY this is occurring.

View::composer('layouts.application', function($view)
{
    $view->with('currentUser', Sentry::currentUser());
});

I'm guessing you are doing View::share in app/start/global.php. This file is invoked by calling parent::setUp() , which is before you've done Sentry::login , and thus, $currentUser will be null. You should either find a way to delay the View::share (using a view composer is one way to do this) or just use Sentry::getUser() in your views.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM