Valentin Hinov (@ValCanBuild) on X

2 min read Original article ↗

Post

Post

  • user avatar

    Lets use this as a @laravelphp learning opportunity. We added a feature to let

    @thankbox

    recipients reply to everyone who had left a message on their Thankbox. Lets look at the code and see what happened 1/7

    user avatar

    Hey, the unit test passed, but our integration one failed. Sorry to people that got spammed. We'll be extra careful now. 🙈🙈🙈

  • user avatar

    This is the code that ran (shortened for brevity) when a recipient replied. The comment makes it pretty clear what we *wanted* it to do. Pretty trivial, right? Get all the messages on this Thankbox that have an email attached or that have a user on them. 2/7

    user avatar

    Why do we need that orWhereHas? It's because we don't require people to register in order leave a message on a Thankbox - for ease of use. They can just leave their email (contributor_email). We don't ask users for their email if they are logged in - we know it. 3/7

    user avatar

    But we naively assumed that the orWhereHas would apply *just* to messages within the Thankbox we were querying. We were fooled by our unit tests, because in our tests we just created one thankbox and a few users so all assertions passed. 4/7

    user avatar

    Instead, the SQL query that ended up being generated was this. Notice where the brackets are. It made our code send an email to people with messages on this Thankbox OR *everyone who has an account and has ever left a message anywhere* 🤦‍♂️ But hey, our tests were passing. 5/7