NameError: uninitialized constant :: Nokogiri

I wrote a test for the model:

describe Video do describe 'searching youtube for video existence' do it 'should return true if video exists' do Video.video_exists?("http://www.youtube.com/watch?v=KgfdlZuVz7I").should be_true end end end 

Here is the model code:

 class Video < ActiveRecord::Base attr_accessible :video_id def self.video_exists?(video_url) video_url =~ /\?v=(.*?)&/ xmlfeed = Nokogiri::HTML(open("http://gdata.youtube.com/feeds/api/videos?q=#{$1}")) if xmlfeed.at_xpath("//openSearch:totalResults").content.to_i == 0 return false else return true end end end 

But he is not mistaken:

 Failures: 1) Video searching youtube for video existence should return true if video exists Failure/Error: Video.video_exists?("http://www.youtube.com/watch?v=KgfdlZuVz7I").should be_true NameError: uninitialized constant Video::Nokogiri # ./app/models/video.rb:6:in `video_exists?' # ./spec/models/video_spec.rb:6:in `block (3 levels) in <top (required)>' Finished in 0.00386 seconds 1 example, 1 failure 

I do not know how to solve this, what could be the problem?

+4
source share
2 answers

The problem was that I did not add gem nokogiri to the Gemfile.

After adding, I removed require 'nokogiri' and require 'open-uri' from the model, and it works.

+10
source

You don't seem to need Nokogiri, so you need to do this.

 uninitialized constant Video::Nokogiri 

- distribution. Ruby knows that the Nokogiri is constant, but does not know where to find it.

In your code, Nokogiri uses an Open-URI to retrieve the content, so you also need require 'open-uri' . Nokogiri reads a file descriptor that returns an Open-URI open .

This section can be written more briefly:

 if xmlfeed.at_xpath("//openSearch:totalResults").content.to_i == 0 return false else return true end 

as:

 !(xmlfeed.at_xpath("//openSearch:totalResults").content.to_i == 0) 

or

 !(xmlfeed.at("//openSearch:totalResults").content.to_i == 0) 
+3
source

Source: https://habr.com/ru/post/1434650/


All Articles