Rspec测试页面内容中的html实体
我正在编写请求规范,并希望测试字符串“Reports»Aging Reports”的存在。 我得到一个错误(无效的多字节字符),如果我直接在我的匹配表达式中输入字符,所以我尝试了这个: page.should have_content("Reports » Aging Reports")
这使测试失败并显示以下消息:
expected there to be content "Reports » Aging Reports" in "\n Reports » Aging Reports\n
我尝试过像.html_safe
这样的东西没有成功。 有没有办法测试包含html实体的文本?
编辑:
这是html源代码的相关区域:
您也可以让测试看一下页面的原始来源:
breadcrumb = 'Reports » Aging Reports' page.body.should include(breadcrumb) expect(page.body).to include(breadcrumb) # rspec 2.11+
话虽如此,我不确定这是最优雅的解决方案。 假设您的链接周围有一个名为.breadcrumb
的类,您只需validationdiv中存在的链接:
within '.breadcrumb' do page.should have_css('a', text: 'Reports') page.should have_css('a', text: 'Aging Reports') expect(page).to have_css('a', text: 'Reports') # rspec 2.11+ expect(page).to have_css('a', text: 'Aging Reports') # rspec 2.11+ end
这样你就可以在breadcrumb块中明确地寻找一个href。
如果你想要的话, html_safe
不会删除html标签。
如果您在测试之前删除html标签,则可以使用sanitize
gem。
# in Gemfile gem 'sanitize' # in testfile require 'sanitize' html = Sanitize.clean(page.body.text) html.should have_content("Reports » Aging Reports")
我找到了暂时使用正则表达式而不是字符串的解决方法:
find('#breadcrumbs').text.should match(/Reports . Aging Reports/)
这将获取breadcrumbs
div的文本,其中包含我正在寻找的文本,因此匹配的范围是有限的。 这很好,但我仍然想知道如何匹配特定的HTML实体。
有时最简单的解决方案是正确的解决方案,事情就是……
page.should have_content("Reports » Aging Reports")