我正在编写请求规范,并希望测试字符串“Reports»Aging Reports”的存在。如果我直接在我的matcher表达式中输入字符,我会收到一个错误(无效的多字节字符),所以我尝试了这个: 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源代码的相关区域:
<a href="/reports">Reports</a> » <a href="/aging_reports">Aging Reports</a>
您也可以让测试看一下页面的原始来源:
breadcrumb = '<a href="/reports">Reports</a> » <a href="/aging_reports">Aging Reports</a>'
page.body.should include(breadcrumb)
expect(page.body).to include(breadcrumb) # rspec 2.11+
话虽如此,我不确定这是最优雅的解决方案。假设有一个名为的类 .breadcrumb
在您的链接周围,您可以只验证div中存在的链接:
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
宝石。
# 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")