Browse Source

Storing flash messages during beforeRender event and restoring them

Jeremy Harris 9 years ago
parent
commit
19954476fd
1 changed files with 34 additions and 1 deletions
  1. 34 1
      src/TestSuite/IntegrationTestCase.php

+ 34 - 1
src/TestSuite/IntegrationTestCase.php

@@ -149,6 +149,21 @@ abstract class IntegrationTestCase extends TestCase
     protected $_csrfToken = false;
 
     /**
+     * Boolean flag for whether or not the request should re-store
+     * flash messages
+     *
+     * @var bool
+     */
+    protected $_rememberFlashMessages = false;
+
+    /**
+     * Stored flash messages before render
+     *
+     * @var null|array
+     */
+    protected $_flashMessages;
+
+    /**
      *
      * @var null|string
      */
@@ -187,6 +202,7 @@ abstract class IntegrationTestCase extends TestCase
         $this->_appArgs = null;
         $this->_securityToken = false;
         $this->_csrfToken = false;
+        $this->_rememberFlashMessages = false;
         $this->_useHttpServer = false;
     }
 
@@ -243,6 +259,17 @@ abstract class IntegrationTestCase extends TestCase
     }
 
     /**
+     * Calling this method will re-store flash messages into the test session
+     * after being removed by the FlashHelper
+     *
+     * @return void
+     */
+    public function enableRememberFlashMessages()
+    {
+        $this->_rememberFlashMessages = true;
+    }
+
+    /**
      * Configures the data for the *next* request.
      *
      * This data is cleared in the tearDown() method.
@@ -425,6 +452,9 @@ abstract class IntegrationTestCase extends TestCase
             $request = $this->_buildRequest($url, $method, $data);
             $response = $dispatcher->execute($request);
             $this->_requestSession = $request['session'];
+            if ($this->_rememberFlashMessages) {
+                $this->_requestSession->write('Flash', $this->_flashMessages);
+            }
             $this->_response = $response;
         } catch (\PHPUnit\Exception $e) {
             throw $e;
@@ -466,10 +496,13 @@ abstract class IntegrationTestCase extends TestCase
         }
         $this->_controller = $controller;
         $events = $controller->eventManager();
-        $events->on('View.beforeRender', function ($event, $viewFile) {
+        $events->on('View.beforeRender', function ($event, $viewFile) use ($controller) {
             if (!$this->_viewName) {
                 $this->_viewName = $viewFile;
             }
+            if ($this->_rememberFlashMessages) {
+                $this->_flashMessages = $controller->request->session()->read('Flash');
+            }
         });
         $events->on('View.beforeLayout', function ($event, $viewFile) {
             $this->_layoutName = $viewFile;