名称错误:未初始化常量::Nokogiri

4

我编写了模型的测试:

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

以下是模型代码:

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

但是它出现了错误:

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

我不知道如何解决这个问题,可能是什么原因呢?


1
你有在任何地方使用过 require 'nokogiri' 吗? - Justin Ko
我本以为在Gemfile中加入了Nokogiri后,它会被自动包含进来。但是,当我在模型文件顶部加入require 'nokogiri'时,它引发了另一个错误:“app/models/video.rb:1:in <top (required)>' app/controllers/videos_controller.rb:1:in <top (required)>' 在加载以下文件时出现此错误: nokogiri” - Иван Бишевац
2个回答

10
问题是因为我没有在 Gemfile 中添加“gem nokogiri”。添加后,我从模型中删除了“require 'nokogiri'”和“require 'open-uri'”,现在它可以正常工作了。

3

看起来你没有要求使用Nokogiri,所以你需要去做那个。

uninitialized constant Video::Nokogiri

这里需要说明的是,Ruby知道"Nokogiri"是一个常量,但不知道它的具体位置。

在你的代码中,Nokogiri依赖于Open-URI来获取内容,所以你还需要require 'open-uri'。Nokogiri读取Open-URI的open返回的文件句柄。

这一部分可以更加简洁地写成:

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

作为:

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

或者:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接