Giovanni Azua Giovanni Azua - 4 months ago 32
Scala Question

Scalatest: should be Matchers with extra description?

I have a

org.scalatest.FunSpec with org.scalatest.Matchers
test that does the following e.g.

val tol = 1e-10
val res = 1.000000000000001
val ref = 1.000000000000000
res should be (ref +- tol)

but it does so in a loop for multiple cases keyed by name, of course I can't change the granularity of the tested code so I get a collection of values with those names associated to them. Therefore for a test above I need to place an extra context or extra description
to reflect to which name it applies. I need something like:

val name : String = ...
res should be (ref +- tol) for name

I can't use
at this point because they are already outside.


It really depends on what you're trying to do, and you should probably add a more complete example of what you're trying to achieve, but you could use describe in the loop. For example:

class TempTest extends FunSpec with Matchers {

  describe("Some example test") {

    (1 to 10).foreach { i => // your loop here

      describe(s"Scenario $i") {
        it("should be equal to itself") {
          i shouldBe i

UPDATE: You could use withClue to add more context to the matcher e.g.:

withClue("Some clarifying message") {
    i shouldBe 5

This will add the clue string to the error if the conditions fails.