I'm implementing some logic that requires code to behave differently in a production environment.
I want to write a test that asserts this actually happens, but I'm having difficulty mocking the environment.
I've seen it suggested to use putenv('APP_ENV=production');
but it doesn't seem to work.
How can I make the test pass?
use Illuminate\Support\Facades\App;
use Tests\TestCase;
class EnvTest extends TestCase
{
public function testEnv()
{
// This assertion is fine
$env = App::environment();
$this->assertEquals('testing', $env);
putenv('APP_ENV=production');
// This assertion fails
$env = App::environment();
$this->assertEquals('production', $env);
}
}
Time: 160 ms, Memory: 18.00MB
There was 1 failure:
1) EnvTest::testEnv
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'production'
+'testing'
I know this question is a year old now, but for those who come looking like I did, this worked for me in 5.8
public function test_config_env()
{
$this->app->detectEnvironment(function() {
return 'production';
});
$this->assertEquals('production', app()->environment()); // pass
}
use App;
//...
public function my_awesome_test()
{
// Number of times method environment() have to be invoked
$number_of_calls_to_method = 2
// Fake, that we have production environment
App::shouldReceive('environment')
->times($number_of_calls_to_method)
->andReturn('production');
// Make here whatever you want in Production environment
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With