In this episode, we tackle a common issue with inviting users to teams: making sure the same email address can't be invited twice to the same team, while still allowing someone to be invited to multiple different teams.
We start by writing a test to ensure that an invite can't be created if the email address has already been used for the current team. We use factories to set up our test data, including pre-creating an invite, and then run our test to verify that things are behaving as expected.
Initially, we add a "unique" validation rule for the email, but quickly run into a snag — this rule makes email addresses unique across the whole table, which isn't what we want. That means someone couldn't be invited to more than one team with the same email, which breaks our desired functionality.
To fix this, we adjust our validation so the uniqueness of the email is scoped only to the team. We also write a complementary test to check that the same email can be used for a different team. After updating our rule to enforce uniqueness for the email within the context of a specific team, we rerun our tests and confirm everything works as it should.
So by the end of this episode, our invites are correctly validated: no double invites to the same team, but the same email can be invited to as many different teams as needed.