【问题标题】:Rspec testing for html entities in page content页面内容中 html 实体的 Rspec 测试
【发布时间】:2011-10-07 17:58:58
【问题描述】:

我正在编写一个请求规范,并想测试字符串“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源码的相关区域:

<a href="/reports">Reports</a> » <a href="/aging_reports">Aging Reports</a>

【问题讨论】:

  • 这可能是因为 HTML 源代码包含 » 而不是 »。更改 HTML 以便使用 » 而不是 »。实际呈现的 HTML 是什么? » 是 HTML 源代码的一部分,还是在 HTML 源代码中定义为 »?请向我们展示源 HTML。不知道为什么“预期”显示»而不是»
  • HTML 实际上是 » »是“”的另一种形式我尝试过的实体,但我已经更新了问题。
  • 看起来 RSpec 正在为您将 » 转换为 »。尝试在测试中包含实际角色。

标签: ruby-on-rails ruby rspec html-entities


【解决方案1】:

您也可以让测试查看页面的原始源代码:

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

通过这种方式,您可以在面包屑块中显式查找 href。

【讨论】:

    【解决方案2】:

    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 &raquo; Aging Reports")
    

    【讨论】:

      【解决方案3】:

      有时最简单的解决方案就是正确的解决方案,而且一切正常......

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

      【讨论】:

      • 我同意这一点。不知道为什么我是 7 七年来这里唯一的支持者。
      【解决方案4】:

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

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

      这会得到breadcrumbs div 的文本,其中包含我要查找的文本,因此匹配的范围是有限的。这很好用,但我仍然很想知道如何匹配特定的 html 实体。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-11
        • 2015-06-17
        • 2013-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多