Reputation: 3657
I'm writing unit tests for an API built in Laravel. I have a database instance specific for running tests against and have configured the phpunit.xml
to tell Laravel to use that db during testing.
However, my issue is when it comes to tests that perform a HTTP request to a route:
$response = $this->json('POST', route('api.login'), [
'email' => '[email protected]',
'password' => 'really.secure.password',
]);
The above request goes via my local network and from the application's point of view this is just another request, it doesn't know this is PHPUnit calling, so the auth token is created in my main database (not the testing database).
Now this feels like a pretty common scenario that I am doing so I'm hoping I've just missed some small tip in all the documentation and tutorials.
One solution which feels a bit hacky is to add some middleware which detects if the user-agent
header of the request is set to "PHPUnit" and somehow change the environment and database values via the middleware. That feels a bit dirty so I'm reluctant to do it without first asking the SO community.
Can you suggest an existing technique or more elegant approach?
Upvotes: 2
Views: 987
Reputation: 1681
@MartinJoiner Have you found a solution to this problem ?
Though its an old question. Here is what I have done, which is not a perfect solution by any means. All db settings are coming from .env file. I have a separate .env.testing which is supposed to be used for testing only. Though phpunit knows the environment is testing , I have done the following in composer.json to ensure tests are using .env.testing
This means when an api call is made during tests, the local system is using .env.testing and ensures testing DB is used for both HTTP and phpunit .
"scripts": {
"test": [
"cp .env.testing .env",
"vendor/bin/phpunit",
"cp .env.example .env"
],
}
And then run tests via composer test
.
However I have a bit of a different but related issue. I hope you may have a look and provide some guidance.
Upvotes: 1