I would like to get full URLs inside emails that get triggered by my tests in CakePHP 3.2. I tried with the full-options for $this->Html->image('image.jpg', ['fullBase' => true])
and $this->Url->build('/', true)
but they don't seem to work in tests.
How can I force full URLs in emails while testing?
There is no host when running an app in the CLI environment as it's not a web request. You'll have to configure the base URL on your own.
Quote from the docs:
App.fullBaseUrl
The fully qualified domain name (including protocol) to your application’s root. This is used when generating absolute URLs. By default this value is generated using the
$_SERVER
environment. However, you should define it manually to optimize performance or if you are concerned about people manipulating theHost
header. In a CLI context (from shells) thefullBaseUrl
cannot be read from$_SERVER
, as there is no webserver involved. You do need to specify it yourself if you do need to generate URLs from a shell (e.g. when sending emails).
So you can either configure it via App.fullBaseUrl
Configure::write('App.fullBaseUrl', 'http://localhost');
or a little more specific so that it only applies to the router, via Router::fullBaseUrl()
Router::fullBaseUrl('http://localhost');
You can either configure it in your application configuration (config/app.php
), so that even on regular web requests your app isn't building it dynamically anmore, and consequently have it available in the test environment too, or, if you just want to apply to the test suite, put it either in your tests bootstrap (tests/bootstrap.php
) to have it apply globally, or set it in your individual test case files.
That's what the CakePHP core test suite is doing it too btw. Whenever you're unsure, having a look at the core tests might give you a hint.
See also
- Cookbook > Configuration > General Configuration
- API > \Cake\Routing\Router::fullBaseUrl()
- https://github.com/cakephp/cakephp/blob/3.2.13/tests/bootstrap.php#L70
- https://github.com/cakephp/.../blob/3.2.13/tests/TestCase/Routing/RouterTest.php#L74
- https://github.com/cakephp/.../3.2.13/tests/TestCase/Routing/RouterTest.php#L520-L529
来源:https://stackoverflow.com/questions/38785795/full-urls-in-emails-in-cakephp-unittest