Events
- Introduction
- Defining events
- Defining listeners
- Dispatching events
- Queued listeners
- Database transactions
- Testing events
Introduction
Events let you decouple the parts of your application, so a single action can trigger several side effects. When a customer places an order, you may want to email a receipt, record an audit log entry, and notify the warehouse. Rather than growing your order code with every new step, dispatch an OrderPlaced event and let independent listeners react to it.
An event is a plain Go struct, and a listener is a function that takes a context and an event. You list your listeners in listeners.All, and your code dispatches events with event.Dispatch. Models also dispatch model events when you create, update, or delete them, and broadcasting lets you push events to the browser over WebSockets.
Defining events
An event is a struct that holds what its listeners need to know. You may keep your events in an events package:
1// events/order_placed.go2package events34type OrderPlaced struct {5 OrderID int646 Email string7 Total int648}1// events/order_placed.go2package events34type OrderPlaced struct {5 OrderID int646 Email string7 Total int648}
An event needs no methods or tags. Copy the IDs and values your listeners need into the event, rather than the *web.Request, so the listeners also work when a command or a test dispatches the event.
Defining listeners
A listener is a function that takes a context.Context and an event, and returns an error. New applications keep listeners in the listeners package. For example, this listener emails an OrderReceipt mailable to the customer:
1// listeners/send_receipt.go2package listeners34import (5 "context"67 "go.laravel.com/mail"89 "app/events"10 "app/mails"11)1213func SendReceipt(ctx context.Context, e events.OrderPlaced) error {14 receipt := mails.OrderReceipt{OrderID: e.OrderID}1516 return mail.To(mail.Addr(e.Email)).Send(ctx, receipt)17}1// listeners/send_receipt.go2package listeners34import (5 "context"67 "go.laravel.com/mail"89 "app/events"10 "app/mails"11)1213func SendReceipt(ctx context.Context, e events.OrderPlaced) error {14 receipt := mails.OrderReceipt{OrderID: e.OrderID}1516 return mail.To(mail.Addr(e.Email)).Send(ctx, receipt)17}
The listener reaches the rest of your application through its ctx, as a handler does through r. Queries and model writes with ctx run on your database, config.From(ctx) returns your configuration, and services.From(ctx) returns your own services, such as a payment provider's client. The listener receives the context that the event was dispatched with, so during a request, auth.User returns the logged-in user.
Registering listeners
A listener runs only once you register it. New applications list their listeners in listeners.All, which bootstrap.Options passes to the application. Wrap each function in laravel.Listen, which takes the event's type from the function's second argument:
1// listeners/listeners.go2package listeners34import laravel "go.laravel.com"56var All = []laravel.Listener{7 laravel.Listen(SendReceipt),8 laravel.Listen(RecordAuditEntry),9}1// listeners/listeners.go2package listeners34import laravel "go.laravel.com"56var All = []laravel.Listener{7 laravel.Listen(SendReceipt),8 laravel.Listen(RecordAuditEntry),9}
An event may have any number of listeners. They run one after another, in the order you list them.
Listening for several events
Sometimes one listener should react to several kinds of events, such as recording an audit entry for every change a user makes. When a listener's event type is an interface, the listener receives every event that implements the interface. For example, if each of your auditable events has an AuditEntry method, one listener can record all of them:
1// listeners/record_audit_entry.go2package listeners34import (5 "context"67 "go.laravel.com/db"8)910type Auditable interface {11 AuditEntry() string12}1314func RecordAuditEntry(ctx context.Context, e Auditable) error {15 return db.Table("audit_entries").Insert(ctx, db.Values{"entry": e.AuditEntry()})16}1// listeners/record_audit_entry.go2package listeners34import (5 "context"67 "go.laravel.com/db"8)910type Auditable interface {11 AuditEntry() string12}1314func RecordAuditEntry(ctx context.Context, e Auditable) error {15 return db.Table("audit_entries").Insert(ctx, db.Values{"entry": e.AuditEntry()})16}
A listener of any receives every event your application dispatches.
Listeners from packages
A package may react to your application's events too, such as sending a quote to each new user. A package registers its listeners in its Register method with app.Listeners:
1func (q *Quotes) Register(app *laravel.Registrar) error {2 app.Listeners(laravel.Listen(q.QuoteOnSignUp))34 return nil5}1func (q *Quotes) Register(app *laravel.Registrar) error {2 app.Listeners(laravel.Listen(q.QuoteOnSignUp))34 return nil5}
A package's listeners run before the application's own listeners of the same event.
Dispatching events
To notify an event's listeners, pass the event to event.Dispatch with a context. For example, given an Order model, this function creates an order and dispatches OrderPlaced:
1// store/orders.go2package store34import (5 "context"67 "go.laravel.com/event"8 "go.laravel.com/model"910 "app/events"11 "app/models"12)1314func PlaceOrder(ctx context.Context, customer models.User, total int64) (models.Order, error) {15 order := models.Order{UserID: customer.ID, Total: total}16 if err := model.Create(ctx, &order); err != nil {17 return models.Order{}, err18 }1920 err := event.Dispatch(ctx, events.OrderPlaced{21 OrderID: order.ID,22 Email: customer.Email,23 Total: total,24 })2526 return order, err27}1// store/orders.go2package store34import (5 "context"67 "go.laravel.com/event"8 "go.laravel.com/model"910 "app/events"11 "app/models"12)1314func PlaceOrder(ctx context.Context, customer models.User, total int64) (models.Order, error) {15 order := models.Order{UserID: customer.ID, Total: total}16 if err := model.Create(ctx, &order); err != nil {17 return models.Order{}, err18 }1920 err := event.Dispatch(ctx, events.OrderPlaced{21 OrderID: order.ID,22 Email: customer.Email,23 Total: total,24 })2526 return order, err27}
Dispatch runs the event's listeners one after another and returns once they've all finished. A handler calls PlaceOrder with r, which is a context.Context, and a command or a job passes the ctx it received.
Failures
If a listener returns an error, the event's remaining listeners don't run, and Dispatch returns that error. A handler that passes the error to web.Fail responds with an error response. The order is already saved, so to keep a failing listener from failing the request, report the error with laravel.Report instead of returning it:
1err := event.Dispatch(ctx, events.OrderPlaced{2 OrderID: order.ID,3 Email: customer.Email,4 Total: total,5})6if err != nil {7 laravel.Report(ctx, err)8}910return order, nil1err := event.Dispatch(ctx, events.OrderPlaced{2 OrderID: order.ID,3 Email: customer.Email,4 Total: total,5})6if err != nil {7 laravel.Report(ctx, err)8}910return order, nil
Inside a database transaction, listeners run after the transaction commits, so db.Transaction reports their errors instead.
Dispatching in the background
When the caller doesn't need to wait for the listeners, such as a listener that pings an analytics service, dispatch the event as background work. laravel.Background runs the dispatch in a goroutine of its own and returns at once:
1placed := events.OrderPlaced{OrderID: order.ID, Email: customer.Email, Total: total}23laravel.Background(ctx, func(ctx context.Context) error {4 return event.Dispatch(ctx, placed)5})1placed := events.OrderPlaced{OrderID: order.ID, Email: customer.Email, Total: total}23laravel.Background(ctx, func(ctx context.Context) error {4 return event.Dispatch(ctx, placed)5})
In a handler, call r.Background with the same function. Because nobody waits for the listeners, Laravel reports their errors. Inside a database transaction, the background work starts only after the transaction commits, and a rollback discards it. When the server shuts down, it waits for background work up to SERVER_SHUTDOWN_TIMEOUT.
Background work is kept only in memory and isn't retried, so a crash or restart can lose it. For work that must complete reliably, use a queued listener.
Queued listeners
When a listener performs slow work, such as sending an email or calling another service, run it on your queue instead. The queue stores the work until a worker runs it, so a queued listener has two parts: a job, whose fields hold what the work needs and whose Handle method does the work, and a function that builds the job from the event. For example, this queued listener replaces the SendReceipt function from Defining listeners:
1// listeners/send_receipt.go2package listeners34import (5 "context"67 "go.laravel.com/mail"89 "app/events"10 "app/mails"11)1213type SendReceipt struct {14 OrderID int6415 Email string16}1718func QueueReceipt(e events.OrderPlaced) SendReceipt {19 return SendReceipt{OrderID: e.OrderID, Email: e.Email}20}2122func (j SendReceipt) Handle(ctx context.Context) error {23 receipt := mails.OrderReceipt{OrderID: j.OrderID}2425 return mail.To(mail.Addr(j.Email)).Send(ctx, receipt)26}1// listeners/send_receipt.go2package listeners34import (5 "context"67 "go.laravel.com/mail"89 "app/events"10 "app/mails"11)1213type SendReceipt struct {14 OrderID int6415 Email string16}1718func QueueReceipt(e events.OrderPlaced) SendReceipt {19 return SendReceipt{OrderID: e.OrderID, Email: e.Email}20}2122func (j SendReceipt) Handle(ctx context.Context) error {23 receipt := mails.OrderReceipt{OrderID: j.OrderID}2425 return mail.To(mail.Addr(j.Email)).Send(ctx, receipt)26}
Register the listener with laravel.ListenQueued, which takes the event's type from the function's argument:
1var All = []laravel.Listener{2 laravel.ListenQueued(QueueReceipt),3}1var All = []laravel.Listener{2 laravel.ListenQueued(QueueReceipt),3}
Dispatching OrderPlaced now pushes a SendReceipt job, so a queue worker runs the listener's work, while the event's other listeners still run in the dispatch. Laravel adds the job type of each queued listener to your queue's jobs, so you don't list it in jobs.All. Inside a database transaction, the job is pushed only after the transaction commits, like any queued job.
The job is an ordinary job, so its Handle may release, delete, or fail its run. The queue stores the job's fields as JSON, so copy the IDs and values the work needs out of the event, as QueueReceipt does. A job field may also hold a model, which the worker reads from the database again before Handle runs. If the model's row has been deleted by then, the worker deletes the job without running it, unless the job's options set FailWhenMissingModels.
Queue options
A receipt email might belong on an emails queue and get a few retries in case your mail provider is down. Give the job a JobOptions method to choose its queue, tries, backoff, and timeout, as for any job:
1func (SendReceipt) JobOptions() queue.Options {2 return queue.Options{3 Queue: "emails",4 Tries: 3,5 Backoff: []time.Duration{time.Minute},6 }7}1func (SendReceipt) JobOptions() queue.Options {2 return queue.Options{3 Queue: "emails",4 Tries: 3,5 Backoff: []time.Duration{time.Minute},6 }7}
To push the job to another connection, or to delay it, call Connection and Delay on the listener when you register it in listeners.All:
1laravel.ListenQueued(QueueReceipt).Connection("redis").Delay(10 * time.Minute)1laravel.ListenQueued(QueueReceipt).Connection("redis").Delay(10 * time.Minute)
The queue stores the job under its type's name, such as app/listeners.SendReceipt. Before you rename or move a queued listener whose jobs may still be waiting, give the job a JobName method that returns the old name.
Job methods
When a queued listener needs more than Handle, give its job any of the optional methods below Handle in this table:
| Method | Purpose |
|---|---|
Handle(ctx) error |
Runs the listener's work on the worker. |
Failed(ctx, |
Cleans up when the job fails for good. |
ShouldQueue() bool |
Returns false to skip pushing the job for this event. |
JobOptions() queue.Options |
Chooses the job's queue, tries, backoff, timeout, and debouncing. |
Middleware() []queue.Middleware |
Returns job middleware that wraps Handle. |
DebounceID() string |
Groups debounced runs. |
For example, this listener awards a gift card for orders of $50 or more (Total is in cents), and logs a warning if every try fails:
1// listeners/reward_gift_card.go2package listeners34import (5 "context"6 "log/slog"78 "go.laravel.com/model"9 "go.laravel.com/queue"1011 "app/events"12 "app/models"13)1415type RewardGiftCard struct {16 OrderID int6417 Total int6418}1920func QueueGiftCard(e events.OrderPlaced) RewardGiftCard {21 return RewardGiftCard{OrderID: e.OrderID, Total: e.Total}22}2324func (j RewardGiftCard) ShouldQueue() bool {25 return j.Total >= 500026}2728func (RewardGiftCard) JobOptions() queue.Options {29 return queue.Options{Queue: "rewards", Tries: 3}30}3132func (j RewardGiftCard) Handle(ctx context.Context) error {33 return model.Create(ctx, &models.GiftCard{OrderID: j.OrderID, Amount: 500})34}3536func (j RewardGiftCard) Failed(ctx context.Context, err error) error {37 slog.WarnContext(ctx, "Couldn't reward a gift card.", "order", j.OrderID, "error", err)3839 return nil40}1// listeners/reward_gift_card.go2package listeners34import (5 "context"6 "log/slog"78 "go.laravel.com/model"9 "go.laravel.com/queue"1011 "app/events"12 "app/models"13)1415type RewardGiftCard struct {16 OrderID int6417 Total int6418}1920func QueueGiftCard(e events.OrderPlaced) RewardGiftCard {21 return RewardGiftCard{OrderID: e.OrderID, Total: e.Total}22}2324func (j RewardGiftCard) ShouldQueue() bool {25 return j.Total >= 500026}2728func (RewardGiftCard) JobOptions() queue.Options {29 return queue.Options{Queue: "rewards", Tries: 3}30}3132func (j RewardGiftCard) Handle(ctx context.Context) error {33 return model.Create(ctx, &models.GiftCard{OrderID: j.OrderID, Amount: 500})34}3536func (j RewardGiftCard) Failed(ctx context.Context, err error) error {37 slog.WarnContext(ctx, "Couldn't reward a gift card.", "order", j.OrderID, "error", err)3839 return nil40}
ShouldQueue runs before the job is pushed, so a skipped event never reaches the queue.
Debouncing listeners
When an event fires repeatedly in quick succession, you may want to handle only the final occurrence. For example, a user who saves their profile five times in a minute should receive one confirmation email, not five. Listen for the model.Updated[models.User] event, and give the job a DebounceFor option and a DebounceID method that groups related events:
1// listeners/send_profile_updated_email.go2package listeners34import (5 "context"6 "strconv"7 "time"89 "go.laravel.com/mail"10 "go.laravel.com/model"11 "go.laravel.com/queue"1213 "app/mails"14 "app/models"15)1617type SendProfileUpdatedEmail struct {18 User models.User `queue:"model"`19}2021func QueueProfileUpdatedEmail(e model.Updated[models.User]) SendProfileUpdatedEmail {22 return SendProfileUpdatedEmail{User: e.Model}23}2425func (SendProfileUpdatedEmail) JobOptions() queue.Options {26 return queue.Options{DebounceFor: time.Minute}27}2829func (j SendProfileUpdatedEmail) DebounceID() string {30 return strconv.FormatInt(j.User.ID, 10)31}3233func (j SendProfileUpdatedEmail) Handle(ctx context.Context) error {34 return mail.To(j.User).Send(ctx, mails.ProfileUpdated{User: j.User})35}1// listeners/send_profile_updated_email.go2package listeners34import (5 "context"6 "strconv"7 "time"89 "go.laravel.com/mail"10 "go.laravel.com/model"11 "go.laravel.com/queue"1213 "app/mails"14 "app/models"15)1617type SendProfileUpdatedEmail struct {18 User models.User `queue:"model"`19}2021func QueueProfileUpdatedEmail(e model.Updated[models.User]) SendProfileUpdatedEmail {22 return SendProfileUpdatedEmail{User: e.Model}23}2425func (SendProfileUpdatedEmail) JobOptions() queue.Options {26 return queue.Options{DebounceFor: time.Minute}27}2829func (j SendProfileUpdatedEmail) DebounceID() string {30 return strconv.FormatInt(j.User.ID, 10)31}3233func (j SendProfileUpdatedEmail) Handle(ctx context.Context) error {34 return mail.To(j.User).Send(ctx, mails.ProfileUpdated{User: j.User})35}
Each user now receives a single email one minute after their last update. Without DebounceID, every SendProfileUpdatedEmail job would replace the ones before it, across all users. To make sure the email still goes out when a user keeps saving, cap the wait with MaxWait, such as queue.Options{DebounceFor: time.Minute, MaxWait: 5 * time.Minute}.
The queue tracks debounced jobs in your default cache store, so use a store that every server shares, such as database or redis. To learn more about debouncing options, check out the queues guide's section on debounced jobs.
Database transactions
Events dispatched inside a database transaction wait until the outermost transaction commits before running their listeners. If the transaction rolls back, Laravel discards the pending events, so listeners never send receipts or read rows that were never saved. Outside a transaction, Dispatch runs listeners immediately. Jobs and broadcasts also wait for transactions to commit.
For example, this version of PlaceOrder saves an order and its payment together, and dispatches OrderPlaced only once both commit:
1// store/orders.go2package store34import (5 "context"67 "go.laravel.com/db"8 "go.laravel.com/event"9 "go.laravel.com/model"1011 "app/events"12 "app/models"13)1415func PlaceOrder(ctx context.Context, customer models.User, total int64) (models.Order, error) {16 order := models.Order{UserID: customer.ID, Total: total}17 err := db.Transaction(ctx, func(ctx context.Context) error {18 if err := model.Create(ctx, &order); err != nil {19 return err20 }2122 payment := models.Payment{OrderID: order.ID, Amount: total}23 if err := model.Create(ctx, &payment); err != nil {24 return err25 }2627 return event.Dispatch(ctx, events.OrderPlaced{28 OrderID: order.ID,29 Email: customer.Email,30 Total: total,31 })32 })3334 return order, err35}1// store/orders.go2package store34import (5 "context"67 "go.laravel.com/db"8 "go.laravel.com/event"9 "go.laravel.com/model"1011 "app/events"12 "app/models"13)1415func PlaceOrder(ctx context.Context, customer models.User, total int64) (models.Order, error) {16 order := models.Order{UserID: customer.ID, Total: total}17 err := db.Transaction(ctx, func(ctx context.Context) error {18 if err := model.Create(ctx, &order); err != nil {19 return err20 }2122 payment := models.Payment{OrderID: order.ID, Amount: total}23 if err := model.Create(ctx, &payment); err != nil {24 return err25 }2627 return event.Dispatch(ctx, events.OrderPlaced{28 OrderID: order.ID,29 Email: customer.Email,30 Total: total,31 })32 })3334 return order, err35}
Inside the transaction, Dispatch returns nil immediately and holds the event until the commit. If a held listener fails after the commit, the order is already saved, so db.Transaction reports the listener's error and returns nil. To learn more about work that waits for a commit, check out the database guide's section on after-commit work.
Dispatch with the ctx that db.Transaction passes to its function. A context from outside the function, such as a handler's r, isn't in the transaction, so its dispatch runs the listeners at once, before the commit.
Running listeners in the transaction
Some listeners must take part in the transaction itself, such as one that reserves stock, which should succeed or roll back alongside the order. Register those listeners with laravel.ListenAtDispatch, so they run immediately when you dispatch the event instead of waiting for the commit:
1// listeners/reserve_stock.go2package listeners34import (5 "context"67 "go.laravel.com/model"89 "app/events"10 "app/models"11)1213func ReserveStock(ctx context.Context, e events.OrderPlaced) error {14 return model.Create(ctx, &models.Reservation{OrderID: e.OrderID})15}1// listeners/reserve_stock.go2package listeners34import (5 "context"67 "go.laravel.com/model"89 "app/events"10 "app/models"11)1213func ReserveStock(ctx context.Context, e events.OrderPlaced) error {14 return model.Create(ctx, &models.Reservation{OrderID: e.OrderID})15}
1var All = []laravel.Listener{2 laravel.ListenAtDispatch(ReserveStock),3 laravel.ListenQueued(QueueReceipt),4}1var All = []laravel.Listener{2 laravel.ListenAtDispatch(ReserveStock),3 laravel.ListenQueued(QueueReceipt),4}
The listener receives the dispatch's ctx, which is in the transaction, so its writes commit or roll back with the order. Its error fails Dispatch, and returning that error from the transaction's function rolls the transaction back. The event's other listeners still wait for the commit. Keep these listeners fast, because the transaction holds its row locks while they run.
Some events belong inside the transaction as a whole, such as a StockReserved event whose every listener writes rows that must roll back with the order. To run every listener of an event at dispatch time, including those registered with laravel.Listen, give the event an AtDispatch method that returns true:
1type StockReserved struct {2 OrderID int643}45func (StockReserved) AtDispatch() bool {6 return true7}1type StockReserved struct {2 OrderID int643}45func (StockReserved) AtDispatch() bool {6 return true7}
Testing events
When you test code that dispatches events, you usually want to check that it dispatched the right event, and test the listeners on their own. eventtest.New installs a fake in your test's application that records dispatched events instead of running their listeners. Pass it the test client, then make assertions on the fake it returns:
1// tests/feature/orders_test.go2package feature_test34import (5 "testing"67 "go.laravel.com/eventtest"89 "app/database/factories"10 "app/events"11 "app/tests"12)1314func TestPlacingAnOrderDispatchesAnEvent(t *testing.T) {15 client := tests.New(t)16 user := client.Create(factories.User)17 dispatched := eventtest.New(client)1819 client.ActingAs(&user).20 PostJSON("/api/orders", map[string]any{"total": 2500}).21 AssertCreated()2223 dispatched.AssertDispatched[events.OrderPlaced]()2425 dispatched.AssertDispatched(func(e events.OrderPlaced) bool {26 return e.Email == user.Email && e.Total == 250027 })2829 dispatched.AssertDispatchedTimes[events.OrderPlaced](1)30}1// tests/feature/orders_test.go2package feature_test34import (5 "testing"67 "go.laravel.com/eventtest"89 "app/database/factories"10 "app/events"11 "app/tests"12)1314func TestPlacingAnOrderDispatchesAnEvent(t *testing.T) {15 client := tests.New(t)16 user := client.Create(factories.User)17 dispatched := eventtest.New(client)1819 client.ActingAs(&user).20 PostJSON("/api/orders", map[string]any{"total": 2500}).21 AssertCreated()2223 dispatched.AssertDispatched[events.OrderPlaced]()2425 dispatched.AssertDispatched(func(e events.OrderPlaced) bool {26 return e.Email == user.Email && e.Total == 250027 })2829 dispatched.AssertDispatchedTimes[events.OrderPlaced](1)30}
You may also call AssertNotDispatched, which takes a type or a match function, and AssertNothingDispatched(). To inspect the recorded events directly, dispatched.Dispatched[events.OrderPlaced]() returns them in the order they were dispatched.
The fake records model events too, such as the model.Created[models.User] event of a user that a factory creates. Create the rows your test needs before you install the fake, as the test above does, so the fake records only what the request dispatched. Each test builds its own application with tests.New, so tests that run in parallel never see each other's events.
Faking selected events
To fake only specific events while all other events run their listeners as usual, name them with eventtest.Only:
1dispatched := eventtest.New(client,2 eventtest.Only(events.OrderPlaced{}, events.OrderCancelled{}),3)1dispatched := eventtest.New(client,2 eventtest.Only(events.OrderPlaced{}, events.OrderCancelled{}),3)
To fake every event except specific ones, use eventtest.Except, such as eventtest.New(client, eventtest.Except(events.OrderShipped{})).
Testing a listener
To test a single listener without running the other listeners of the same event, call the listener with client.Context() and an event. The context carries the application under test, so the listener's queries run on the test's database, and fakes you install on the client, such as the mail fake, apply to the listener too:
1func TestReservingStock(t *testing.T) {2 client := tests.New(t)34 if err := listeners.ReserveStock(client.Context(), events.OrderPlaced{OrderID: 42}); err != nil {5 t.Fatal(err)6 }78 client.AssertDatabaseHas("reservations", db.Values{"order_id": 42})9}1func TestReservingStock(t *testing.T) {2 client := tests.New(t)34 if err := listeners.ReserveStock(client.Context(), events.OrderPlaced{OrderID: 42}); err != nil {5 t.Fatal(err)6 }78 client.AssertDatabaseHas("reservations", db.Values{"order_id": 42})9}
With RefreshDatabase, listeners that wait for a commit still run once your application's own transaction commits, even though the test rolls everything back afterwards.
Testing queued listeners
A queued listener pushes a job. To verify that dispatching an event queued the listener's job, use the queue fake:
1func TestPlacingAnOrderQueuesTheReceipt(t *testing.T) {2 client := tests.New(t)3 user := client.Create(factories.User)4 queued := queuetest.New(client)56 client.ActingAs(&user).7 PostJSON("/api/orders", map[string]any{"total": 2500}).8 AssertCreated()910 queued.AssertPushed(func(job queuetest.Job[listeners.SendReceipt]) bool {11 return job.Job.Email == user.Email && job.Queue == "emails"12 })13}1func TestPlacingAnOrderQueuesTheReceipt(t *testing.T) {2 client := tests.New(t)3 user := client.Create(factories.User)4 queued := queuetest.New(client)56 client.ActingAs(&user).7 PostJSON("/api/orders", map[string]any{"total": 2500}).8 AssertCreated()910 queued.AssertPushed(func(job queuetest.Job[listeners.SendReceipt]) bool {11 return job.Job.Email == user.Email && job.Queue == "emails"12 })13}
Because the event fake keeps listeners from running at all, nothing reaches the queue when both fakes are installed. Use the queue fake on its own when you test queued listeners.
To test the job's work, such as a release or a failure, build the job with your function and run one attempt with client.Attempt:
1job := listeners.QueueReceipt(events.OrderPlaced{2 OrderID: 42,4 Total: 2500,5})67client.Attempt(job).AssertSucceeded()1job := listeners.QueueReceipt(events.OrderPlaced{2 OrderID: 42,4 Total: 2500,5})67client.Attempt(job).AssertSucceeded()