Specs2字符串比较不适用于should

时间:2016-11-23 10:01:40

标签: scala specs2

我正在使用specs2,我的理解是mustshould是等效的(请参阅http://docs.ansible.com/ansible/playbooks_tags.html#special-tags),使用其中一个只是个人偏好。

但是,在比较字符串时,使用must的以下测试有效:

import org.specs2.mutable._

class StringEqualWithMust extends Specification {

  "string comp " should {
    "abc" must beEqualTo("abc")
  }
}

但使用should的相同测试将无法编译:

import org.specs2.mutable._

class StringEqualWithShould extends Specification {

  "string comp " should {
    "abc" should beEqualTo("abc")
  }
}

编译错误是:

StringEqualWithShould.scala:7: overloaded method value should with alternatives:
[error]   (fs: => org.specs2.specification.core.Fragments)(implicit p1: org.specs2.control.ImplicitParameters.ImplicitParam1)org.specs2.specification.core.Fragments <and>
[error]   (f: => org.specs2.specification.core.Fragment)org.specs2.specification.core.Fragment
[error]  cannot be applied to (org.specs2.matcher.BeEqualTo)
[error]     "abc" should beEqualTo("abc")
[error]           ^
[error] one error found

为什么在比较字符串时,mustshould之间存在差异?

我正在使用sbt 0.13.8,scala 2.12.0和specs2 3.8.6

1 个答案:

答案 0 :(得分:0)

困难来自这样一个事实:should可用于打开一组示例,但也可用于描述期望。您可以通过混合以下特征来解决此问题

import org.specs2.specification.core._
import org.specs2.control.ImplicitParameters._
import org.specs2.specification.dsl.mutable.ExampleDsl

trait NoShouldBlock extends ExampleDsl {

  override def describe(s: String) = super.describe(s)

  implicit class block(d: String) {
    def >>(f: => Fragment): Fragment = describe(d).>>(f)
    def >>(fs: => Fragments)(implicit p1: ImplicitParam1): Fragments =     describe(d).>>(fs)(p1)
  }

}

然后编写您的规范,如

class StringEqualWithShould extends org.specs2.mutable.Specification with NoShouldBlock {

  "string comp" >> {
    "first example" >> {
      "abc" should beEqualTo("abc")
    }
    "second example" >> {
      "def" should beEqualTo("def")
    }
  }
}