Refactoring and fixing tests