Skip to content

Instantly share code, notes, and snippets.

@zgabievi
Last active May 3, 2017 08:00
Show Gist options
  • Save zgabievi/092bb3d2c8d8441189e8c895ffe58f04 to your computer and use it in GitHub Desktop.
Save zgabievi/092bb3d2c8d8441189e8c895ffe58f04 to your computer and use it in GitHub Desktop.
Way to make TDD easy, with exception handling and factory helpers
{
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
},
"files": ["tests/helpers.php"]
}
}
<?php
function create($class, $attributes = [], $times = null)
{
return factory($class, $times)->create($attributes);
}
function make($class, $attributes = [], $times = null)
{
return factory($class, $times)->make($attributes);
}
<?php
namespace Tests;
use App\Exceptions\Handler;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
protected function setUp()
{
parent::setUp();
$this->disableExceptionHandling();
}
protected function signIn($user = null)
{
$user = $user ?: create('App\User');
$this->actingAs($user);
return $this;
}
// Hat tip, @adamwathan.
protected function disableExceptionHandling()
{
$this->oldExceptionHandler = $this->app->make(ExceptionHandler::class);
$this->app->instance(ExceptionHandler::class, new class extends Handler {
public function __construct() {}
public function report(\Exception $e) {}
public function render($request, \Exception $e) {
throw $e;
}
});
}
protected function withExceptionHandling()
{
$this->app->instance(ExceptionHandler::class, $this->oldExceptionHandler);
return $this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment