Refactor and fix test