2014-09-04 51 views
1

第一次在這裏詢問。我會切入正題。我試圖測試一個控制器的渲染視圖,我還沒有找到任何明確的方法來做到這一點。特別是,我試圖做的是測試呈現的.gsp的實際內容;即,如果呈現的html頁面包含項目列表(例如,列表,例如<ul><li>標記)或頁面應該顯示的任何其他內容。這可能嗎?或者甚至有效的方法來測試這種事情?我試圖做這樣的事情:在Grails 2.3.8中測試.gsp頁面的呈現內容

控制器:

class ConnectedPairController { 

    def show(int id) { 
     //Some logic to populate collections and stuff 

     render(view:"show.gsp", model:['pqc':cp.getPath(), 
          'connected':cp.getPage(), 
          'instance':coll, 
          'pagesCollection':colPages]) 
    } 

測試:

@TestFor(ConnectedPairController) 

    class ConnectedPairControllerSpec extends Specification { 
     void "test show"() {  
     when: 
      controller.show(4) //4 being the id of the content I want to display 
     then: 
      controller.response.text.contains "Some string or html tag the page should display" 
     } 
    } 

但返回的文本爲空。也許這是應該的,但是有沒有辦法獲得渲染的內容?

我的文檔中找到什麼是沒有用的(至少是我想要做的沒有),因爲恕我直言只測試瑣碎的東西,像.gsp正在呈現什麼,或者變量的內容:

@TestFor(SimpleController) 
class SimpleControllerSpec extends Specification { 

    void 'test home'() { 
    when: 
    controller.home() 

    then: 
    view == '/simple/homePage' 
    model.title == 'Hello World' 
    } 
} 

我希望我已經夠清楚了。感謝您的時間。 PS:我正在使用Grails 2.3.8。如果您需要與環境等有關的其他信息,請告訴我。

+0

如果我今天晚些時候有更多的時間,我會把這個鏈接變成一個答案。同時,請嘗試以下方法:http://www.grailstraining.com/groovy/testing-your-gsp-views-from-integration-tests – EpicVoyage 2014-09-16 18:44:11

回答

0

@ColinHarrington感謝您的回答,並對延誤表示歉意。我嘗試了這些網站上的內容,但無論呈現的是什麼視圖(.gsp)(就像一個簡單的頁面,只是呈現變量的內容),render方法總是返回null(甚至不是空字符串)。

控制器:

class TestingController { 

    def index() { 
     render view: "testing.gsp", model: [test:"Test String"] 
    } 
} 

測試:

import grails.test.mixin.TestMixin 
import grails.test.mixin.web.GroovyPageUnitTestMixin 
import spock.lang.Specification 


@TestMixin(GroovyPageUnitTestMixin) 
class TestingControllerSpec extends Specification { 
    def controller 

    def setup() { 
     controller = testFor(TestingController) 
    } 

    void "test something"() { 
     when: 
      controller.index() 
     then: 
      render (view:"/testing/testing.gsp", model:model) == "Test String" 
    } 
} 

測試結果:

test something(webbluefinder.TestingControllerSpec) 
| 
Condition not satisfied: 
render (view:"/testing/testing.gsp", model:model) == "Test String" 
|           |  | 
null          |  false 
             [test:Test String] 

我也試過HAKI先生的做法,並得到了相同的結果。 你碰巧知道爲什麼會發生這種情況?謝謝你的時間。