Refactor and try to write integration test