In this episode, we tackle a sneaky bug in our team management feature: when you remove a user from a team, their roles don't get detached. That means if you add the same person back in later, they end up collecting roles they shouldn't have (like both 'member' and 'admin'), which definitely isn't what we want!
We start off by demonstrating the problem step-by-step, inviting a user to a team, changing their role, removing them, and then re-adding them. Sure enough, their previous role sticks around, which could cause all kinds of permission headaches.
Next, we write a test to capture this scenario—making sure that when a user is removed, their roles within that team are wiped out too. We play around with different ways to set up the test, using manual setup so we've got total control over what roles get assigned before and after removal.
To fix things, it's just a small change in our controller: when removing a team member, we also detach all their roles. After running our updated tests, everything goes green—problem solved! So now, users get a clean slate each time they're added back to a team, preventing any ghost roles from haunting your permissions.