refactor: Tests refactored so that the defer function will be called in the right place