Integrating out heavy fields in the path integral using the background-field method: general formalism