Refactor filtering and add a spec for it