我正在尝试使用PHPUnit测试Laravel 4中我的控制器上的一些操作。
public function testAboutPage()
{
$this->client->request('GET', 'about');
$this->assertResponseOk();
}
另外,我将变量绑定到App::before()
过滤器中的视图。
App::before(function($request)
{
View::share('usersCount', User::remember(60)->count());
}
这是我的控制器:
class PagesController extends BaseController
{
public function about()
{
return View::make('pages.about')->withTitle("About");
}
}
但是,在测试中未定义变量之前,我的测试失败了。这是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
我该怎么做才能解决这个问题?在浏览器或生产中查看时,该变量很好。
答案 0 :(得分:2)
从文档中可以看出,过滤器已被禁用。我认为这只是指路由文件中定义的过滤器,但它也会在过滤器之前/之后影响应用程序。
注意:在测试环境中禁用路由过滤器。要启用它们,请将Route :: enableFilters()添加到测试中。
我已将此添加到我的测试中,以使它们变绿。
public function setUp()
{
parent::setUp();
Route::enableFilters();
}