bostinait's avatar

Testing an API with Guzzle

As the title suggests I want to create some PHPUnit tests that use guzzle to retrieve responses from an API I am building.

As part of the setUp method I run the migrate and db:seed command that loads the DB into an SQLite DB in memory

Now the issue I'm having, or rather the solution I'm trying to find is when guzzle hits http://tenant.example.com/api/foo I want the app to be in testing mode, rather than local mode so it uses the sqlite db.

The only way I can think of achieving this is to send a custom header via guzzle that Laravel picks up "somewhere" and sets the environment variable to testing.

Is this the best/only approach? Are there any other ways?

Update I should add that I am dipping my toe into L5 since we are approaching January, and manually setting the environment within the app may not be possible?

Update 2 Switched to separate MySQL DB for creating a testing DB, and I can hack the environment variable by adding the below (still not sure of the best place to put something like this, plus its feeling incredibly hacky)

putenv('APP_ENV=testing')
0 likes
2 replies
zefman's avatar

There is no need to use guzzle for this, Laravel TestCase has a built in helper for making requests to your site in tests. One of Jeffrey's tuts has a good api testing helper function:

 public function getJson($uri, $params = [])
 {
        return json_decode($this->call('GET', $uri, $params)->getContent());
 }

Please or to participate in this conversation.