You are here

public function EmailActivationTest::testSavedSearchUpdate in Search API Saved Searches 8

Tests that updating of saved searches is handled correctly.

An email should only be triggered when the saved search is already active and its e-mail address changes.

File

tests/src/Kernel/EmailActivationTest.php, line 254

Class

EmailActivationTest
Tests whether activation mails are sent correctly.

Namespace

Drupal\Tests\search_api_saved_searches\Kernel

Code

public function testSavedSearchUpdate() {
  $search = SavedSearch::create([
    'type' => 'default',
    'label' => 'Test search 1',
    'mail' => 'foo@example.net',
  ]);
  $this
    ->assertEquals(SAVED_NEW, $search
    ->save());
  $this
    ->sendMails();

  // Assert that the search was deactivated.
  $this
    ->assertFalse($search
    ->get('status')->value);

  // Assert an e-mail was sent but just save it here and empty the mail
  // storage.
  $captured_emails = \Drupal::state()
    ->get('system.test_mail_collector');
  $this
    ->assertNotEmpty($captured_emails);
  $first_mail = reset($captured_emails);
  \Drupal::state()
    ->delete('system.test_mail_collector');

  // Changing the mail address of the saved search at this point shouldn't
  // trigger another mail (since the saved search isn't active yet).
  $result = $search
    ->set('mail', 'bar@example.net')
    ->save();
  $this
    ->sendMails();
  $this
    ->assertEquals(SAVED_UPDATED, $result);
  $captured_emails = \Drupal::state()
    ->get('system.test_mail_collector');
  $this
    ->assertEmpty($captured_emails);
  $this
    ->assertFalse($search
    ->get('status')->value);

  // Activate the saved search.
  $controller = new SavedSearchController();
  $response = $controller
    ->activateSearch($search, $search
    ->getAccessToken('activate'));
  $this
    ->assertInstanceOf(RedirectResponse::class, $response);
  $this
    ->assertTrue($search
    ->get('status')->value);

  // Now that the saved search is active, the mail address can't be changed
  // without activating the saved search again. (Since the token stays the
  // same, this should produce exactly the same mail as the first time –
  // except for the recipient's mail address, of course.)
  $result = $search
    ->set('mail', 'test@example.net')
    ->save();
  $this
    ->sendMails();
  $this
    ->assertEquals(SAVED_UPDATED, $result);
  $captured_emails = \Drupal::state()
    ->get('system.test_mail_collector');
  $this
    ->assertNotEmpty($captured_emails);
  $first_mail['to'] = 'test@example.net';
  $this
    ->assertEquals($first_mail, reset($captured_emails));
  $this
    ->assertFalse($search
    ->get('status')->value);
}