不幸的是config(['key' => 'newValue'])
,在 Dusk 设置中不起作用(用于覆盖配置值),大概是因为它会更改运行测试的系统的配置,而不是打开以执行流程的无头浏览器的体验。
有时我看不出需要临时更改某个 Dusk 测试的 env 值。
例如,通常在“黄昏连接”时临时设置QUEUE_DRIVER=sync
,但在一项特定测试中,我需要检查数据库中“作业”表中的值。
在升级到 Laravel >=5.8(以及更新版本的 DotEnv)之前,我能够使用之前在 Dusk 测试中调用的这个函数$this->browse(...
:
/**
* Overrides any .env variables for Dusk tests. https://laracasts.com/discuss/channels/testing/how-to-change-env-variable-config-in-dusk-test
* The changes exist only for that one test because of tearDown.
* Remember that you need to be using `php artisan dusk` instead of `phpunit`.
* https://stackoverflow.com/questions/54407784/laravel-dusk-how-to-change-config-values-before-each-test-for-the-browser#comment103224655_54407784
*
* @param array $variables
*/
protected function overrideDuskEnv($variables = []) {
$path = self::DOT_ENV;
if (file_exists($path)) {
$contentToPrepend = '';
foreach ($variables as $key => $value) {// Convert all new parameters to expected format
$contentToPrepend .= $key . '="' . $value . '"' . PHP_EOL;
}
$originalFileContents = $this->envContents;
$comment = '# ==============================================' . PHP_EOL . '# VARIABLES ABOVE THIS LINE are from "' . __FUNCTION__ . '" function in DuskTestCase ( https://laracasts.com/discuss/channels/testing/how-to-change-env-variable-config-in-dusk-test )' . PHP_EOL;
file_put_contents($path, $contentToPrepend . $comment . $originalFileContents); //"If they are appended, it doesn't seem to take priority."
} else {
throw new \Exception('Could not find env file to override!');
}
}
我可以这样称呼它:$this->overrideDuskEnv(['QUEUE_DRIVER' => 'sync']);
但在最近的 Laravel 版本中,环境变量是不可变的(请参阅“只读 env Helper”)。
我怎样才能实现我的目标,Dusk.env.dusk.local
用于大多数测试,但某些测试可能略有不同?