Same name and namespace in other branches
  1. 8.9.x core/lib/Drupal/Core/Test/AssertMailTrait.php \Drupal\Core\Test\AssertMailTrait::assertMailString()
  2. 9 core/lib/Drupal/Core/Test/AssertMailTrait.php \Drupal\Core\Test\AssertMailTrait::assertMailString()

Asserts that the most recently sent email message has the string in it.

Parameters

string $field_name: Name of field or message property to assert: subject, body, id, ...

string $string: String to search for.

int $email_depth: Number of emails to search for string, starting with most recent.

string $message: (optional) A message to display with the assertion. Do not translate messages: use \Drupal\Component\Render\FormattableMarkup to embed variables in the message text, not t(). If left blank, a default message will be displayed.

4 calls to AssertMailTrait::assertMailString()
ContactPersonalTest::testPersonalContactForm in core/modules/contact/tests/src/Functional/ContactPersonalTest.php
Tests that the opt-out message is included correctly in contact emails.
ContactPersonalTest::testSendPersonalContactMessage in core/modules/contact/tests/src/Functional/ContactPersonalTest.php
Tests that mails for contact messages are correctly sent.
UserAdminTest::testUserAdmin in core/modules/user/tests/src/Functional/UserAdminTest.php
Registers a user and deletes it.
UserMailNotifyTest::testUserRecoveryMailLanguage in core/modules/user/tests/src/Kernel/UserMailNotifyTest.php
Tests recovery email content and token langcode is aligned.

File

core/lib/Drupal/Core/Test/AssertMailTrait.php, line 81

Class

AssertMailTrait
Provides methods for testing emails sent during test runs.

Namespace

Drupal\Core\Test

Code

protected function assertMailString($field_name, $string, $email_depth, $message = '') {
  $mails = $this
    ->getMails();
  $string_found = FALSE;

  // Cast MarkupInterface objects to string.
  $string = (string) $string;
  for ($i = count($mails) - 1; $i >= count($mails) - $email_depth && $i >= 0; $i--) {
    $mail = $mails[$i];

    // Normalize whitespace, as we don't know what the mail system might have
    // done. Any run of whitespace becomes a single space.
    $normalized_mail = preg_replace('/\\s+/', ' ', $mail[$field_name]);
    $normalized_string = preg_replace('/\\s+/', ' ', $string);
    $string_found = str_contains($normalized_mail, $normalized_string);
    if ($string_found) {
      break;
    }
  }
  if (!$message) {
    $message = new FormattableMarkup('Expected text found in @field of email message: "@expected".', [
      '@field' => $field_name,
      '@expected' => $string,
    ]);
  }
  $this
    ->assertTrue($string_found, $message);
}