تماشای این درس نیاز به اشتراک حرفه‌ای دارد.

Writing the Job Test0:00

Let's prepare a test. Make test, and we'll call it sendInvoiceTest. All right. And let's see, we'll make this super simple. It sends an invoice to a User. All right, so let's see. Given I have a User and an Invoice, when I dispatch the sendInvoice job, a notification should be sent to the User. Very, very simple. You can expand on this if you need to. Okay. Given I have a User, let's just say User::factory()->create(). Next, an Invoice. Well, an Invoice is just a plain old PHP object. So what I could do is instantiate Invoice here, and I need to give it an id, the total, the chargeDate, and paid. So why don't we use named arguments here? An id can be a stub. How about invoiceStub 123? Next, the total can be, how about, 15.00. The chargeDate can be a Carbon instance. How about last week? And then finally, yeah, finally, was it paid? And we'll set that to true. Yeah. Okay, so we have our Invoice. Next,

Faking Notifications1:07

and cents. The chargeDate can be a Carbon instance. How about last week? And then finally, yeah, finally, was it paid? And we'll set that to true. Yeah. Okay, so we have our invoice. Next, when I dispatch the sendInvoice job. All right, sendInvoice, dispatch. Finally, a notification should be sent to the user. So when we are working with notifications, here's what you can do. Pull in the Notification facade and call a fake method. And basically what this does is it swaps out the underlying instance for the facade with a notification fake. This is actually one of the coolest things that Laravel does. Laravel facades get a lot of criticism, but you know what, one of the benefits, I think this is incredibly cool. You call a method, it swaps out the underlying instance, and now you get a whole new API when you're interacting with that notification object. Notice all of these assertion helpers. The ones we want would be, how about, assertSentTo.

Asserting Notification Sent1:58

underlying instance, and now you get a whole new API when you're interacting with that notification object. Notice all of these assertion helpers. The ones we want would be, how about, assertSentTo. We'll give it a User, the Notification class, and then an optional callback. Okay, so let's do this at the bottom. We have faked notifications, so I will now say notification::assertSentTo($user, $invoicePaid); Yeah. All right, have a look. Given I have a User, given I have an Invoice, when I dispatch this job...oh, and you know what, real quick, I forgot to provide the constructor args, didn't I? Okay, $invoiceUser, then a Notification should be sent. All right, so arrange, act, assert. All right, let's give it a run. And it passes, so we're good to go. The only thing to keep in mind, it took about five seconds, and that's because, in this case, our test actually is deferring to BrowserShot and Puppeteer.

Testing NotificationsFacade Fakes

دوست دارید گاهی خبرهای Laracasts را ایمیل کنیم؟