我正在尝试编写一个Specs2测试,它将测试一个片段的输出以响应通常从模板传入的不同参数,但我还是无法弄清楚如何去做.
例如,使用此div中的代码段标注:
<div class="lift:Snippet.method?param1=foo"></div>
Run Code Online (Sandbox Code Playgroud)
我将参数param1传递给代码段.我的代码片段看起来像这样:
class Snippet {
def method(in:NodeSeq):NodeSeq = {
val param1 = S.attr("param1") openOr ""
param1 match {
case "foo" => //do something
case "bar" => //do something else
case _ => //do yet another thing
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以在我的测试中,我想测试代码片段如何响应不同的param1值
class SnippetTest extends Specification {
"Snippet" should {
"do something" in {
val html = <ul>
<li class="first">
<li class="second">
<li class="third">
</ul>
//I need to set param1 here somehow
val out = Snippet.method(html)
//then check that it did what it was supposed to
out.something must be "xyz"
}
}
}
Run Code Online (Sandbox Code Playgroud)
如何设置param1?
我是一个很大的时间scala和提升newb(来自python + django),所以如果我咆哮错误的树,请指导我到正确的.我想可能就是这种情况,我一整天都在谷歌搜索,并没有发现任何与此类似的远程问题.
谢谢,
布莱克
Bla*_*ake 11
好的,我已经弄明白了.这个问题没有引起太多兴趣,但是如果有人在谷歌上搜索相同的问题/问题,这里是你如何做到这一点:
Lift的"S"对象需要添加我们的任意属性,以便在询问时为我们的代码段提供我们想要测试的属性.不幸的是,有两个问题.首先,仅在收到http请求时初始化"S"对象.其次,S.attr是不可改变的.
Lift有一个名为mockweb的包,它允许你制作模拟的http请求.该软件包的文档通常涉及测试会话和用户登录等等,但它也提供了将"S"初始化为规范测试的一部分的机制.
初始化S的第一个问题是通过将我们的测试类定义为WebSpec的扩展而不是规范(WebSpec是mockweb包的一部分并扩展Specification),并在规范定义期间调用"withSFor"来解决,这将初始化"S" "
处理S.attr不可变的第二个问题用"S"方法"withAttrs"解决."withAttrs"会执行您提供的代码块,其中包含常规属性和您在地图中提供的属性.您的任意属性只能暂时从S.attr获得
以下是我原始问题的测试,该问题已被修改以解决2个问题:
import net.liftweb.mockweb._
class SnippetTest extends WebSpec {
"Snippet" should {
"do something" withSFor("/") in {
val html = <ul>
<li class="first">
<li class="second">
<li class="third">
</ul>
//here I set param1
var m = new HashMap[String, String]
m += "param1" -> "foo"
val s = new Snippet()
//then tell S to execute this block of code
//with my arbitrary attributes.
//'out' will be the NodeSeq returned by s.method
val out = S.withAttrs(S.mapToAttrs(m)){
s.method(html)
}
//then check that it did what it was supposed to
out.something must be "xyz"
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:清晰度