2010-08-23 47 views
2

Rails進行測試視圖助手,我需要測試以下幫助:在使用RSpec

def display_all_courses 
    @courses = Course.all 

    output = "" 

    for course in @courses do 
    output << content_tag(:li, :id => course.title.gsub(" ", "-").downcase.strip) do 
     concat content_tag(:h1, course.title) 
     concat link_to("Edit", edit_course_path(course)) 
    end 
    end 

    return output 
end 

,我想知道,如果有,我可以測試這種輸出方式。基本上,我只想測試一下幫手是否給我正確數量的元素,也許是沒有任何課程的情況。

我首先想到的是做這樣的事情:

describe DashboardHelper do 
    describe display_all_courses do 
    it "should return an list of all the courses" do 
     7.times{Factory(:course) 
     html = helper.display_all_courses 
     html.should have_selector(:li) 
    end 
    end 
end 

,這工作得很好。但是,如果我將:count選項添加到has_selector調用中,它突然失敗,任何人都可以幫我弄清楚爲什麼?

回答

-8

顯然,模板是最好的方法。

+0

你能解釋這個答案嗎? – nathanvda 2011-10-14 14:09:00

+0

是的。解釋會很好。 – sambehera 2013-03-21 20:44:40

1

也許它可以幫助將HTML視爲XML? 在這種情況下this link可以提供幫助。

它定義了一個匹配器have_xml這可能正是你所需要的。 雖然我知道它會更好,如果have_tag也只會對字符串起作用。

+0

哦,我倒會考慮這個,感謝擡起頭。 – TheDelChop 2010-08-23 15:51:10

5

我相信你要找的是have_tag和with_tag RSpec的助手

describe DashboardHelper do 
    describe display_all_courses do 
    it "should return an list of all the courses" do 
     7.times{ Factory(:course) } 
     helper.display_all_courses.should have_tag('ul') do 
     with_tag('li', 3) 
     end 
    end 
    end 
end