Skip to content

Instantly share code, notes, and snippets.

@filippotoso
Created May 22, 2023 11:23
Show Gist options
  • Save filippotoso/82b3f4992eade2cf79c152e7361c73b0 to your computer and use it in GitHub Desktop.
Save filippotoso/82b3f4992eade2cf79c152e7361c73b0 to your computer and use it in GitHub Desktop.
[Laravel] Http::fakeRequest() macro to easily fake POST/PATH/DELETE requests
<?php
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Arr;
Http::macro('fakeRequest', function ($method, $url, $payload = [], $response = null) {
Http::fake(function (Request $request) use ($method, $url, $payload, $response) {
if ($request->url() != $url) {
return;
}
if (strtoupper($request->method()) != strtoupper(trim($method))) {
return;
}
$match = collect(Arr::dot($payload))
->reduce(function ($carry, $value, $dot) use ($request) {
return $carry && (Arr::get($request->data(), $dot) == $value);
}, true);
if ($match) {
return is_array($response) ? Http::response($response) : $response;
}
});
});
// Usage
Http::fakeRequest('post', 'https://www.example.com', ['test' => 1], ['done' => 1]);
dump(Http::post('https://www.example.com', ['test' => 1])->json());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment