Skip to content

Instantly share code, notes, and snippets.

@bmadigan
Forked from Vasiliy-Bondarenko/WebhooksTest.php
Created June 16, 2017 02:19
Show Gist options
  • Save bmadigan/70c05207b08a8f3f4f88eb64666934e5 to your computer and use it in GitHub Desktop.
Save bmadigan/70c05207b08a8f3f4f88eb64666934e5 to your computer and use it in GitHub Desktop.
Webhooks testing experiment. Just for fun :)
<?php
//Route::get('/', function () {
// return view('welcome');
//});
if (app()->environment('testing')) {
Route::get('/webhook', function () {
return response()->json(["ok"]);
});
}
<?php
namespace Tests\Feature;
use Tests\TestCase;
use Tests\withTestingEnvironment;
use Zttp\Zttp;
class WebhooksTest extends TestCase
{
use withTestingEnvironment;
/** @test */
public function test_route()
{
$this->withTestingEnvironment(function(){
// action
$result = Zttp::get(url('/webhook'));
// assertions
$this->assertEquals(["ok"], $result->json());
});
}
}
<?php
// Extracted from \Laravel\Dusk\Console\DuskCommand
// I've just changed .env file
namespace Tests;
use Dotenv\Dotenv;
trait withTestingEnvironment
{
public function withTestingEnvironment($callback)
{
if (file_exists(base_path($this->envFile()))) {
if (file_get_contents(base_path('.env')) !== file_get_contents(base_path($this->envFile()))) {
$this->backupEnvironment();
}
$this->refreshEnvironment();
}
return tap($callback(), function () {
if (file_exists(base_path($this->envFile())) && file_exists(base_path('.env.backup'))) {
$this->restoreEnvironment();
}
});
}
/**
* Get the name of the Dusk file for the environment.
*
* @return string
*/
protected function envFile()
{
return '.env.testing';
}
/**
* Backup the current environment file.
*
* @return void
*/
protected function backupEnvironment()
{
copy(base_path('.env'), base_path('.env.backup'));
copy(base_path($this->envFile()), base_path('.env'));
}
/**
* Restore the backed-up environment file.
*
* @return void
*/
protected function restoreEnvironment()
{
copy(base_path('.env.backup'), base_path('.env'));
unlink(base_path('.env.backup'));
}
/**
* Refresh the current environment variables.
*
* @return void
*/
protected function refreshEnvironment()
{
(new Dotenv(base_path()))->overload();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment