I always think this about garlic, chilli, onion, etc. Feeling all tough, naturally designed to punish whatever's just eaten it. Then humans be like, "OOOOO that's yum. Add a bit more."
We like plants that offer a challenge, apparently. We probably evolved to like these chemicals because we refused to be beaten and just ended up liking them.
"animal: evolves to run away from predators as a defense mechanism"
humans: ayo, catch that shit and put it in circle with wood so they can't leave, since, you know, they like to move. Also posts provide all their food and water and let them fuck to make more. Eat them with the evil plants.
ayo evil plants aren’t evil enough. Let’s make little more evil baby plants and from those even more evil baby plants and let’s name the really evil one after a combination of a U.S. state and death itself and then put that shit on the tasty movers
If you search the web you're bound to find what I'm about to broach over but humans are pretty much the real life orcs, if we think about it.
We tolerate serious injuries - even losing limbs - heal at a crazy speed and still remain functional, tolerate foods that other animals consider toxic and as predators we don't get tired and because of that we evolved an entirely new form of predation called stalking strategy, where we can just give chase to prey until they just fall from exhaustion, as our walking is incredibly low on energy consumption and our complex brain allows us to learn patterns on how and where prey are and behave.
Things like onions, garlic, chili and spices have anti microbial properties. This is why warmer countries tends to have spicier food, it protect from food poisoning.
Passing through the digestive tract of a mobile animal is a good way for plants to disperse seeds and reproduce. It makes sense that some plants would be naturally repulsive to some animals and attractive to others.
Also the plants and the animals evolved together. If you're the only animal in the desert that can chomp on a cactus, you're going to survive and pass on your genes.
We don't know whether they evolved these chemicals to prevent being eaten by animals though. People have tested spicy (capsaicin based) foods with mice, and found that mice actually seemed to like or not really react to spicy foods. This means that capsaicin did not evolve to protect against rodents like initially thought.
In fact, we now know that capsaicin is a very powerful antifungal chemical. Chili peppers naturally grow in hot, humid environments where fungi thrive. There also aren't many rodents in those areas. So the spiciness experienced by mammals like humans is just a side effect that didn't really affect its evolution.