The bit you write that is not quite accurate is:
"So if you are in the context of a course, then you check if their role (like a teacher) has the capibility"
A user does not have a role (in a particular context) they probably have several. The most normal case is to have two roles:
Suppose we are in course Roles 101, then user Matt has two roles. Authenticated user inherited from the system context, and Student from the course context.
The same two roles would apply in the module context of any activity in that course.
A more complex example, with three roles, would apply if you were a Moderator in one particular forum in that course.
Therefore, when you check a capability, you are checking the capability of the user in that context, not the capability of one of their roles. Naturally, there have to be rules for when the two roles have different permission. If you really want to know, read section 13.2 of http://www.aosabook.org/en/moodle.html.
To help understand all this, go to the Check permissions page in any context in Moodle. (You can find the link to this in the settings block, but is slighly different places depending on the type of context.) You select a user, and then it will list all the roles they have in this context, and show you all the relevant capabilties, and whether the user has them or not.
Finally, to explain user context. If I go and look at your user profile, then my ability to do that is checked in the user context for your user id. (Although user profiles are a bit more complex than that. There are other privacy settings that may affect it, in addition to the simple has_capabiltiy check.)