【问题标题】:Unit testing with rspec2 and Nokogiri使用 rspec2 和 Nokogiri 进行单元测试
【发布时间】:2013-01-23 10:37:24
【问题描述】:

我需要阅读第三方公共网站。目前我可以通过 Nokogiri 做到这一点,但是我在使用 rspec 编写一些单元测试时遇到了麻烦。

我有这个 HTML <div>:

<div class="user">
  <div class="name">User Name</div>
</div>

在我的阅读器模型中,我有 name 方法,它从 HTML 中读取名称:

class SampleReader
    def name(html_div)
      html_div.css('name')
    end
end

在我的 RSpec 测试用例中,我将上述 HTML &lt;div&gt; 作为字符串传递给 name 方法,我收到以下错误:

undefined method `css' for #<String:0x007fd8a0b39c98>

我相信这是因为 Nokogiri 无法将字符串识别为 HTML,所以如果有人可以帮助我编写测试用例,我将不胜感激。而且,如果可能,我的首选选项是仅将 &lt;div&gt; 字符串而不是整个 HTML 页面源代码传递给该方法。

  • 我使用的是 Rails 3.2.9
  • Rspec2
  • Nokogiri

【问题讨论】:

    标签: ruby ruby-on-rails-3 nokogiri rspec2


    【解决方案1】:

    您需要将 HTML 字符串包装为 Nokogiri 文档:

    require 'nokogiri'
    
    str = <<-HTML
    <div class="user">
      <div class="name">User Name</div>
    </div>
    HTML
    
    class SampleReader
      def name(html_div)
        doc = Nokogiri::HTML(html_div)
        doc.css('.name').text
      end
    end
    
    reader = SampleReader.new
    puts reader.name(str) #=> "User Name"
    

    另外,别忘了upgrade your application to rails 3.2.11

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-06
      • 2011-02-20
      • 2015-09-16
      • 2015-09-01
      相关资源
      最近更新 更多