Rails Minitest:尝试使用 assert_select 时出现关于 "document_root_element" 的错误

Rails Minitest: Error about "document_root_element" when trying to use assert_select

在 Rails 应用程序中,我正在为助手 class 编写 Minitest 单元测试,它生成 returns 一些 HTML (用作正文外发电子邮件的内容)。我正在使用 assert_select 来验证生成的 HTML.

中是否存在特定元素

当测试为 运行 时,带有 assert_select 的行抛出此错误:

Minitest::UnexpectedError: NotImplementedError: Implementing document_root_element makes assert_select work without needing to specify an element to select from.

这是我的 (minimal/simplified) 测试 class 代码:

class MyEmailBodyGeneratorTest < ActiveSupport::TestCase
  include Rails::Dom::Testing::Assertions

  def test_generate_email_body
    generator = MyEmailBodyGenerator.new
    generator.generate_email_body

    assert_select 'p.salutation', count: 1
  end
end

关于实施 document_root_element 的错误是什么意思?我的代码中没有使用该名称的方法。

发生此错误是因为测试没有(以更典型的 Rails 方式)向 Rails 控制器发出 HTTP 请求,因此 assert_select 不会自动知道 HTML 要检查的内容,因为没有 HTML 响应。

如错误消息所示,您可以通过在测试 class 中实现名为 document_root_element 的方法来解决此问题,并将其 return 作为 [=20] 的根节点=] 你想要检查。例如:

class MyEmailBodyGeneratorTest < ActiveSupport::TestCase
  include Rails::Dom::Testing::Assertions

  def test_generate_email_body
    generator = MyEmailBodyGenerator.new
    @email_body_html = generator.generate_email_body

    assert_select 'p.salutation', count: 1
  end

  def document_root_element 
    Nokogiri::HTML::Document.parse(@email_body_html)
  end
end

(有关将包含 HTML 的字符串解析为表示 HTML 中元素的对象树的更多信息,请参阅 Method to parse HTML document in Ruby?。)