SkyWalker
SkyWalker

Reputation: 14309

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 name 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 it and describe at this point because they are already outside.

Upvotes: 3

Views: 1067

Answers (2)

Denis Rosca
Denis Rosca

Reputation: 3459

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.

Upvotes: 6

Alexander Arendar
Alexander Arendar

Reputation: 3425

Probably GivenWhenThen can be used in order to add context to the tests reporting. I am not sure how exactly you wrap your multiple tests in the loop, but here is the idea:

import org.scalatest.{GivenWhenThen, WordSpec}

/**
  * Created by alex on 10/3/16.
  */
class Temp extends WordSpec with GivenWhenThen{
  val names = List("Alex", "Dana")
  for(name <- names)yield{
    "Reversing a name " + name + " two times" should {
      "result in the same name" in{
        Given("name " + name)
        When("reversed two times")
        val reversed = name.reverse.reverse
        Then("it should be the same")
        assert(name === reversed)
      }
    }
  }
}

Upvotes: 1

Related Questions