gpt4 book ai didi

php - 测试 Laravel Controller 时 View 中的 undefined variable

转载 作者:行者123 更新时间:2023-11-28 20:31:30 24 4
gpt4 key购买 nike

我正在尝试使用 PHPUnit 在 Laravel 4 中的 Controller 上测试一些操作。

public function testAboutPage()
{
$this->client->request('GET', 'about');

$this->assertResponseOk();
}

此外,我在 App::before() 过滤器中将一个变量绑定(bind)到我的 View 。

App::before(function($request)
{
View::share('usersCount', User::remember(60)->count());
}

这是我的 Controller :

class PagesController extends BaseController
{
public function about()
{
return View::make('pages.about')->withTitle("About");
}
}

但是,在测试中 undefined variable 之前,我的测试失败了。这是 PHPUnit 的失败输出。

12) PagesControllerTest::testAboutPage
ErrorException: Undefined variable: usersCount (View: app/views/layouts/application.blade.php) (View: app/views/layouts/application.blade.php)

app/storage/views/ed261635437f52c903a09b2774ce5a92:20
vendor/laravel/framework/src/Illuminate/View/Engines/PhpEngine.php:41
vendor/laravel/framework/src/Illuminate/View/Engines/CompilerEngine.php:56
vendor/laravel/framework/src/Illuminate/View/View.php:134
vendor/laravel/framework/src/Illuminate/View/View.php:102
vendor/laravel/framework/src/Illuminate/View/View.php:76
app/storage/views/5993084368b648c9a244ec6637315755:18
vendor/laravel/framework/src/Illuminate/View/Engines/PhpEngine.php:37
vendor/laravel/framework/src/Illuminate/View/Engines/CompilerEngine.php:56
vendor/laravel/framework/src/Illuminate/View/View.php:134
vendor/laravel/framework/src/Illuminate/View/View.php:102
vendor/laravel/framework/src/Illuminate/View/View.php:76
vendor/laravel/framework/src/Illuminate/Http/Response.php:70
vendor/symfony/http-foundation/Symfony/Component/HttpFoundation/Response.php:202
vendor/laravel/framework/src/Illuminate/Routing/Router.php:1413
vendor/laravel/framework/src/Illuminate/Routing/Router.php:1003
vendor/laravel/framework/src/Illuminate/Routing/Router.php:968
vendor/laravel/framework/src/Illuminate/Foundation/Application.php:738
vendor/laravel/framework/src/Illuminate/Foundation/Application.php:708
vendor/symfony/http-kernel/Symfony/Component/HttpKernel/Client.php:81
vendor/symfony/browser-kit/Symfony/Component/BrowserKit/Client.php:319
app/tests/controllers/PagesControllerTest.php:109

我该怎么做才能解决这个问题?在浏览器或生产环境中查看时,该变量没有问题。

最佳答案

从文档中可以看出过滤器被禁用了。我认为这只是指在路由文件中定义的过滤器,但它也会影响应用程序之前/之后的过滤器。

Note: Route filters are disabled when in the testing environment. To enable them, add Route::enableFilters() to your test.

我已将此添加到我的测试中,使它们变绿。

public function setUp()
{
parent::setUp();

Route::enableFilters();
}

关于php - 测试 Laravel Controller 时 View 中的 undefined variable ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21619038/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com