使用 RSpec 测试 Rails 中的视图助手
我需要测试以下助手:
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
我想知道是否有一种方法可以测试其输出。基本上,我只是想测试助手是否为我提供了正确的 li 元素数量,也许在没有任何课程的情况下也是如此。
我的第一个想法是做这样的事情:
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 选项添加到 have_selector 调用中,它会突然失败,任何人都可以帮我找出原因吗?
I need to test the following helper:
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
and I'm wondering if there is a way that I can test the output of this. Basically, I just want to test that the helper gets me the correct number of li elements, and maybe the case when there aren't any courses.
My first thought is to do something like this:
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
and this works just fine. However, if I add the :count option to the have_selector call it suddenly fails, can anybody help me figure out why that is?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我相信您正在寻找的是 have_tag 和 with_tag RSpec 助手
I believe what you were looking for was have_tag and with_tag RSpec helpers
也许将 html 视为 xml 会有所帮助?
在这种情况下 此链接可能会有所帮助。
它定义了一个匹配器
have_xml
,这可能正是您所需要的。尽管我知道如果
have_tag
也适用于字符串会更好。Maybe it could help to treat the html as xml?
In that case this link could help.
It defines a matcher
have_xml
which could be just what you need.Although i understand it would be nicer if the
have_tag
would just work on strings too.显然,模板是实现此目的的最佳方法。
Clearly a template is the best way to do this.