Summer Sale! All accounts are 50% off this week.

mjlovefl's avatar

Testing Laravel Slack Notifications always fail

Not sure what I am doing wrong here, but no matter what I try my test using the example in the Laravel docs never passes. Everything else works just fine. But the test will not pass.

I have Notifiable Model call SlackWebHook

class SlackWebhook extends Model
{

    use Notifiable;

    protected $table = 'slack_webhooks';


    /**
     *
     * The endpoint for Slack notifications
     *
     * @return mixed
     */
    public function routeNotificationForSlack(){

        return $this->url;

    }
}

My Notification looks like (I removed all the message content for clarity)

class DailySlackGiftCardReportNotification extends Notification
{

    use Queueable;

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $webhook
     * @return array
     */
    public function via( $webhook )
    {
        return ['slack'];
    }


    /**
     * Get the slack representation of the notification.
     *
     * @param  mixed  $webhook
     * @return SlackMessage
     */
    public function toSlack( $webhook )
    {

        $message = new SlackMessage();

        $message->success()
            ->content('Hello');

        return $message;

    }


}

And my test based on the Laravel Docs using assertSentTo()

 /**
     * Test Slack Notification.
     *
     * @test
     * @return void
     */
    public function daily_gift_card_slack_notification_sent()
    {

        Notification::fake();

        $webhook = SlackWebhook::where('channel', '@gcstats')->first();

        Notification::assertSentTo(
            $webhook, DailySlackGiftCardReportNotification::class
        );
    }

If I try an AssertNotSentTo it passes. :) Of course, I would like it to pass being sent.

Any ideas what might be going on?

Thanks, Mike

0 likes
1 reply
SMancuso's avatar

You might need to use testing methods for on demand notifications: Notification::assertSentOnDemand(DailySlackGiftCardReportNotification::class);

Docs: https://laravel.com/docs/9.x/mocking#on-demand-notifications:~:text=)%3B-,On%2DDemand%20Notifications,-If%20the%20code

Since Laravel creates an AnonymousNotifiable behind the scene when you have a notifiable in your model, you could also use: Notification::assertSentTo(new AnonymousNotifiable(), DailySlackGiftCardReportNotification::class);

Please or to participate in this conversation.