Fix failing spec and refactor some code