Codeception / module-yii2

Codeception module for Yii2 framework
MIT License
16 stars 36 forks source link

Add method to delete sent emails during tests #53

Closed DBX12 closed 2 years ago

DBX12 commented 2 years ago

Please excuse me directly opening a pull request, but I found this highly helpful on my own projects and thought it might be helpful to the community as well.

This PR adds a method deleteSentEmails() to the module which allows clearing the email "buffer" of the Yii instance. This is helpful if you are using Specify and want to use the seeEmailIsSent() assertion in one specify clause and dontSeeEmailIsSent() in a following clause. Since the first clause sent an email, the second assertion will fail. Clearing the sent emails at the start of the second clause allows you to test properly.


I'm participating in hacktoberfest, so I would be very happy if you could either mark the PR with an hacktoberfest-accepted label, approve it or merge it before 31st October 2021 if you deem it useful :) If you don't think it is helpful, let me know and I withdraw the PR.

SamMousa commented 2 years ago

I don't think people should be doing this manually. These caches (there's more than just email) are cleared on every test. Regarding Specify, could you provide a sample of test code? Because I'd think that you could separate the tests and this would be a non issue.

That said, the code itself LGTM. So this is only a question of whether we should want to expose it in this way.

DBX12 commented 2 years ago

Hmm, I can't judge on if you should delete the caches manually or not, but I can provide a code example where I (would) use it.

public class CustomerTest extends \Codeception\Test\Unit
{
    public function testSendNewsletter()
    {
        $this->specify('Method sendNewsletter()')
            ->should('send an email if customer allows newsletters', function () {
                $customer = new Customer(['wantsNewsletter' => true]);
                $customer->sendNewsletter();
                $this->tester->seeEmailIsSent(1);
            })
            ->shouldNot('send an email if customer does not want newsletters', function () {
                // here I would need to clear the email buffer for the rest of the shouldNot() to succeed
                $customer = new Customer(['wantsNewsletter' => false]);
                $customer->sendNewsletter();
                $this->tester->dontSeeEmailIsSent();
            });
    }
}

Of course, actual usecases would be more complex and I quickly drafted this example but I think it shows my point.

DBX12 commented 2 years ago

Thank you for accepting the PR. Could someone please put an hacktoberfest-accepted label on it so it counts towards the completion of hacktoberfest? :)

DBX12 commented 2 years ago

Thanks Sam :)