Skip to content

Instantly share code, notes, and snippets.

@Sammyjo20
Created June 10, 2024 11:14
Show Gist options
  • Save Sammyjo20/c54412c5c416e567f7e67222729f2e2f to your computer and use it in GitHub Desktop.
Save Sammyjo20/c54412c5c416e567f7e67222729f2e2f to your computer and use it in GitHub Desktop.
Lazy Man's Saloon Fake
/**
* Lazy Man's Saloon Fake
*
* This will record every request that you make in your application and store it in a folder
* based on the name of the test. This is incredibly powerful, but I wouldn't recommend it
* for every request if you are doing the same things over as it will waste API calls.
*
* @return void
*/
function lazyFakeSaloon(): void
{
Saloon::fake([
'*' => function (PendingRequest $pendingRequest) {
$url = $pendingRequest->getUrl();
$body = $pendingRequest->body()?->all() ?? [];
// You might want to strip anything out of the body here like authentication
$body = json_encode($body, JSON_THROW_ON_ERROR);
// Remove the "__pest_evaluable_" prefix from test names
$testName = Str::after(test()->name(), '__pest_evaluable_');
// Prepend the request name to help debugging
$requestClassName = explode('\\', $pendingRequest->getRequest()::class);
$requestClassName = end($requestClassName);
return MockResponse::fixture($testName . '/' . $requestClassName . ':' . md5($url . $body));
},
]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment