Emil L
Emil L

Reputation: 21081

Testing a snippet in Lift

I am making a simple snippet that should pass a Box[String] with the requests user-agent to a helper class that passes back the css classes that should be added to the html element. I am doing this since it seems tricky to get Lift to supply a html respons with conditional comments like those in html5boilerplate. This is what I have now and it works:

class LiftBoilerplate {

   def render = "html [class+]" #> getClassForUserAgent(S.request)

   private def getClassForUserAgent(request:Box[Req]) = request match {
       case Full(r) => LiftBoilerplateHelper.getHtmlClass(r.userAgent)
       case _ => ""
   }
}

My problem is that I'd like to write a unit test for this like:

object LiftBoilerplateSpecs extends Specification {

  val session = new LiftSession("", randomString(20), Empty)

  "LiftBoilerplate" should {
    "add 'no-js' to the class of an html tag element" in {

      val snippet = new LiftBoilerplate
      val result = snippet.render(<html><head></head><body>test</body></html>)

      result must ==/(<html class="no-js"><head></head><body>test</body></html>)
    }
  }
}

This test fails since S.request is Empty. What should I do to supply the snippet with a mocked request with a userAgent in it?

So far I have looked at http://www.assembla.com/spaces/liftweb/wiki/Unit_Testing_Snippets_With_A_Logged_In_User
and
http://www.assembla.com/spaces/liftweb/wiki/Mocking_HTTP_Requests
but I do not understand how to achive my goal.

Upvotes: 5

Views: 421

Answers (1)

Johnny Everson
Johnny Everson

Reputation: 8601

To make the request and apply it automatically in each test example you will need to use the Trait AroundExample to wrap each test in a S.init call:

object LiftBoilerplateSpecs extends Specification with AroundExample {

  val session = new LiftSession("", randomString(20), Empty)

  def makeReq = {
    val mockRequest = new MockHttpServletRequest("http://localhost")
    mockRequest.headers = Map("User-Agent" -> List("Safari"))

    new Req(Req.NilPath, "", GetRequest, Empty, new HTTPRequestServlet(mockRequest, null),
      System.nanoTime, System.nanoTime, false,
      () => ParamCalcInfo(Nil, Map(), Nil, Empty), Map())
  }

  def around[T <% Result](t: => T) = S.init(makeReq, session)(t)

  "LiftBoilerplate" should {
    "add 'no-js' to the class of an html tag element" in {

      val snippet = new LiftBoilerplate
      val result = snippet.render(<html><head></head><body>test</body></html>)

      result must ==/(<html class="no-js"><head></head><body>test</body></html>)
    }
  }
}

Upvotes: 3

Related Questions