Created
September 14, 2018 23:04
-
-
Save kaphert/6845c03472b1d0c52ce5782219363cb5 to your computer and use it in GitHub Desktop.
Assert that blade view files are loaded with PHPUnit in Laravel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Laravel + PHPUnit assert that blade files are being loaded. | |
* | |
* Trait AssertView | |
*/ | |
trait ViewAssertions | |
{ | |
protected $__loadedViews; | |
protected function captureLoadedViews() | |
{ | |
if (!isset($this->__loadedViews)) { | |
$this->__loadedViews = []; | |
$this->app['events']->listen('composing:*', function ($view, $data = []) { | |
if ($data) { | |
$view = $data[0]; // For Laravel >= 5.4 | |
} | |
$this->__loadedViews[] = $view->getName(); | |
} | |
); | |
} | |
} | |
/** | |
* Assert that all of the given views are loaded. | |
* - expectViewFiles('path.to.view') | |
* - expectViewFiles(['path.to.view', 'path.to.other.view']) | |
* - expectViewFiles('path.to.view', 'path.to.other.view') | |
* | |
* @param string|array $paths | |
*/ | |
public function expectViewFiles($paths) | |
{ | |
$paths = is_array($paths) ? $paths : func_get_args(); | |
$this->captureLoadedViews(); | |
$this->beforeApplicationDestroyed(function () use ($paths) { | |
$this->assertEmpty( | |
$viewsLoaded = array_diff($paths, $this->__loadedViews), | |
'These expected view files were not loaded: [' . implode(', ', $viewsLoaded) . ']' | |
); | |
}); | |
} | |
/** | |
* Assert that none of the given views are loaded. | |
* - doesntExpectViewFiles('path.to.view') | |
* - doesntExpectViewFiles(['path.to.view', 'path.to.other.view']) | |
* - doesntExpectViewFiles('path.to.view', 'path.to.other.view') | |
* | |
* @param string|array $paths | |
*/ | |
public function doesntExpectViewFiles($paths) | |
{ | |
$paths = is_array($paths) ? $paths : func_get_args(); | |
$this->captureLoadedViews(); | |
$this->beforeApplicationDestroyed(function () use ($paths) { | |
$this->assertEmpty( | |
$viewsLoaded = array_intersect($this->__loadedViews, $paths), | |
'These unexpected view files were loaded: ['.implode(', ', $viewsLoaded).']' | |
); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: