rubyruby-on-rails-3nokogirirspec2

Unit testing with rspec2 and Nokogiri


I have a requirement to read a third-party public website. Currently I am able to do this via Nokogiri, but I'm having trouble writing some unit tests using rspec.

I have this HTML <div>:

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

In my Reader model I have the method name, which reads the name from the HTML:

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

In my RSpec test case I pass the above HTML <div> as a string to the name method and I get the following error:

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

I believe it's because Nokogiri cannot identified the string as HTML. How can I write the test case? My preferred option is to pass only the <div> string, not the entire HTML page source, to the method.


Solution

  • You'll need to wrap the HTML string as a Nokogiri document:

    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"
    

    Also, don't forget to upgrade your application to rails 3.2.11.