If the crew never leave the plane, have they really entered the foreign country? What about if the crew leaves the plane, but not the airport? How do crews of international flights keep up with all of the visas they may need?
It all depends on the laws of the country that the crew is visiting. Some do and some don't. Many do unless they have a reciprocal agreement with the pilot's country, in which case they don't.
This would be a great question for a specific country pair, or even if you want to know the laws about a specific country (in which case we could give the actual requirements), but the best answer for a general question like this is "it depends".
In some cases, the crew isn't even required to clear customs unless they are leaving airport property. Other times they have to clear as soon as they land.
Part of qualifying for a route with the airlines is making sure that you have the required visas. Having two passports help a lot in getting multiple visas, because they can keep flying internationally while the visa application is in process.
Addressing the "If the crew never leave the plane, have they really entered the foreign country?" question only -- yes.
I've done numerous turns to Canada, Mexico and the Bahamas where we just drop off passengers, pick up the next load and fly back to the US (specifically IAH or EWR in my case). When you get back to the US, you will go through customs unless the station you did the turn at is a pre-clearance station (e.g. passengers go through US customs before boarding). There are no pre-clearance stations in Mexico that I know of, but Canada has many and there are also a few in Europe. My experience is all in scheduled part-121 operations, and this may vary for other operations.
If you get off the plane during the turn (aside from pre-flight duties) then you get to go through the local customs, immigration and security screening to get back on your plane. This was quite painful in airports like Montreal where the walk to customs and back to the plane can be quite long.