Thursday, December 10, 2015

Testing in Yii 2.0 with Codeception - Fixture Data

I'll admit it -- I'm a phpunit addict. Switching to codeception has been a bit of a struggle for me, just because it feels like it should be intuitive, but it's different enough from what I'm used to that it's taken me a few days to really wrap my head around it. My biggest struggle? Trying to get fixture data to automatically load and unload when functional and acceptance tests are run. I finally dug through the yii2-app-advanced code and discovered the FixtureHelper!! The FixtureHelper is the missing link in getting your fixture data to automagically load and unload when the functional and acceptance tests are run.

Friday, December 4, 2015

Flash Messages and Redirects in Yii2

Using Flash messages in Yii 1.1.* is something that I have done for so long, and so commonly, that I take it completely for granted. Whenever a user performs some action and the processing generates some information I want to convey back, I plug that information into a success, warning, info or error flash message, pop in a redirect for that situation and VOILA! After my processes are finished, the flash message is displayed to the user.

For example, in Yii 1.1.*, I have a handy action that is called if a user needs to retrieve their password from the database. It was written well back, around 1.0.6-ish, but still gets the job done nicely. Look up the user by the posted email, if the user is found, send the user an email and set a success message, otherwise, set an error message. Once that's done, redirect the user to the previous page. Otherwise, notify them that there was an error and keep going on.

When I converted this particular action to Yii2 it kept losing my flash messages. If I took out the redirect after successfully processing and sending the email, it was fine -- but I need the redirect to prevent inadvertent multiple form submissions etc. What to do?!? After scouring the internet and Yii forums, and finding multiple instances of people complaining about it not working but no good solutions or notes other than 'working as intended', I finally - FINALLY - realized that it is the redirect method itself that is, while stopping any output to the screen, not actually stopping the currently processed action. If I was more observant, I would have noticed it in the example of a controller redirect here: