【问题标题】:Rails Minitest: Error about "document_root_element" when trying to use assert_selectRails Minitest:尝试使用 assert_select 时出现关于“document_root_element”的错误
【发布时间】:2021-09-22 20:04:03
【问题描述】:

在 Rails 应用程序中,我正在为帮助程序类编写 Minitest 单元测试,该帮助程序类生成并返回一些 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.

这是我的(最小/简化的)测试类代码:

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 的错误是什么意思?我的代码中没有具有该名称的方法。

【问题讨论】:

    标签: ruby-on-rails minitest


    【解决方案1】:

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

    正如错误消息所暗示的,您可以通过在测试类中实现一个名为document_root_element 的方法并让它返回您要检查的 HTML 的根节点来解决此问题。例如:

    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?。)

    【讨论】:

      猜你喜欢
      • 2014-05-01
      • 2023-04-01
      • 1970-01-01
      • 2017-05-15
      • 1970-01-01
      • 2013-07-23
      • 1970-01-01
      • 2020-06-24
      • 2014-02-05
      相关资源
      最近更新 更多