laradan's avatar

How to assert an URL has been called but another URL no

I would like to test a controller that makes a request to an certain URL (EG: http://example.com/api/say-hello) but it does not make a request to another URL (EG: http://example.com/api/say-bye-bye).

The controller function I want to test looks like this:

public function callApis(Request $request)
{
    $data = $this->validate($request, [
        'say_bye_bye' => 'nullable|boolean',
    ]);

    Http::get('http://example.com/api/say-hello');

    if ($data['say_bye_bye']) {
        Http::get('http://example.com/api/say-bye-bye');
    }
}

In my integration tests, I want to make sure that:

  • If the parameter say_bye_bye is TRUE then both of the API endpoints /api/say-hello and /api/say-bye-bye must be called.
  • If the parameter say_bye_bye is FALSE then just the API /api/say-hello has to be called and the API endpoint /api/say-bye-bye must NOT be called.

So far I managed to verify if one or two calls have been made using Http::assertSentCount(int $count).

The solution can be getting the sequence of URLs called by the controller I'm testing, but it seems like there is no way.

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

There are assertSent and assertNotSent methods on the Http fake; so for example, in the case where the boolean is false, you could make the following assertions

// Boolean is FALSE

Http::fake();

// Call your controller endpoint
$this->get('whatever', ['say_bye_bye' => false]);

Http::assertSent(function (Request $request) {
    return $request->url() == 'http://example.com/api/say-hello';
});
Http::assertNotSent(function (Request $request) {
    return $request->url() == 'http://example.com/api/say-bye-bye';
});
1 like
laradan's avatar

Just tried out now and it worked :) Thanks!

Please or to participate in this conversation.