Question

I'm trying to create a specs2 matcher that asserts the validity of a File extension (by reusing the existing endWith matcher). However I get a type error. How could I get around it?

import java.io.File
import org.specs2.mutable.Specification
import org.specs2.matcher.{ Expectable, Matcher }

class SampleSpec extends Specification {
  def hasExtension(extension: => String) = new Matcher[File] {
    def apply[S <: File](actual: Expectable[S]) = {
      actual.value.getPath must endWith(extension)
    }
  }
}

Here's the compiler error:

<console>:13: error: type mismatch;
 found   : org.specs2.matcher.MatchResult[java.lang.String]
 required: org.specs2.matcher.MatchResult[S]
             actual.value.getPath must endWith(extension)
Was it helpful?

Solution

You can indeed use the ^^ operator (taking inspiration from the parser combinators operators) and simply write:

def hasExtension(extension: =>String) = endWith(extension) ^^ ((_:File).getPath)

For reference the various ways of creating custom matchers are presented here.

OTHER TIPS

Okay, I've got it working by using the ^^ operator which adapts between matcher types. It looks like a functor's map function to me.

def hasExtension(extension: => String) = new Matcher[File] {
  def apply[S <: File](actual: Expectable[S]) = {
    actual must endWith(extension) ^^ ((file: S) => file.getPath)
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top