Search code examples
scalamatcherspecs2scala-cats

Specs2 Matchers for Validated and ValidatedNel


I did not find specs2 matchers for ValidatedNel of cats so I am writing matchers like that:

import cats.data._
import cats.implicits._
import org.specs2.matcher.Matcher

type ValidationFailure = String

type ValidationResult[A] = ValidatedNel[ValidationFailure, A]

def beValid: Matcher[ValidationResult[_]] =
  beTrue ^^ ((_: ValidationResult[_]).isValid)

def beInvalid(failure: ValidationFailure): Matcher[ValidationResult[_]] =
  beEqualTo(failure.invalidNel)

def beInvalid[A: Monoid](failures: ValidationFailure*): Matcher[ValidationResult[A]] =
  beEqualTo(failures.toList foldMap (_.invalidNel[A]))

Does it make sense ? How would you suggest improve it ?


Solution

  • I think deriving matchers from other matchers is nice because it gives you some quick win. However the failure messages might not be great. For example the beValid matcher will fail by telling you that a value is not true. So I suggest to write something like:

    def beValid: Matcher[ValidationResult[_]] = { actual: ValidationResult[_] =>
      (actual.isValid, s"$actual is not valid")  
    }
    

    Also a PR in the specs2-cats module would be greatly appreciated if you have the time :-).