问题 Rspec测试页面内容中的html实体


我正在编写请求规范,并希望测试字符串“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> &raquo; <a href="/aging_reports">Aging Reports</a>


6526
2017-10-07 17:58


起源

这很可能是因为HTML源包含一个 » 而不是一个 &raquo;。更改HTML以便您使用 &raquo; 代替 »。什么是实际呈现的HTML?是个 » HTML源代码的一部分或定义为 &raquo; 在HTML源代码?请告诉我们源HTML。不确定为什么“预期”会出现 &#187; 代替 &raquo;但是。 - Zabba
HTML实际上是&raquo; »是&raquo的另一种形式;我试过的实体,但我已经更新了这个问题。 - MWean
看起来RSpec正在转换 &raquo; 成 » 为你。尝试在测试中包含实际角色。 - thomasfedb


答案:


您也可以让测试看一下页面的原始来源:

breadcrumb = '<a href="/reports">Reports</a> &raquo; <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。


6
2017-10-24 22:07





html_safe 不会删除html标签,如果那就是你想要的。

如果您在测试之前删除html标签,则可以使用 sanitize 宝石。

# in Gemfile
gem 'sanitize'

# in testfile
require 'sanitize'
html = Sanitize.clean(page.body.text)
html.should have_content("Reports &raquo; Aging Reports")

3
2018-06-21 11:05





我找到了暂时使用正则表达式而不是字符串的解决方法:

find('#breadcrumbs').text.should match(/Reports . Aging Reports/)

这得到了文本 breadcrumbs div,包含我正在寻找的文本,因此匹配的范围是有限的。这很好,但我仍然想知道如何匹配特定的HTML实体。


1
2017-10-09 16:30





有时最简单的解决方案是正确的解决方案,事情才有效......

page.should have_content("Reports » Aging Reports")

0
2017-09-18 07:28