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

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

4

2 回答 2

10

问题是因为我没有添加gem nokogiri到 Gemfile。

添加它后,我require 'nokogiri'require 'open-uri'模型中删除了它,它可以工作。

于 2012-09-18T02:32:36.340 回答
3

听起来你不需要 Nokogiri,所以你需要这样做。

uninitialized constant Video::Nokogiri

是赠品。Ruby 知道“Nokogiri”是一个常数,但不知道在哪里可以找到它。

在您的代码中,Nokogiri 依赖 Open-URI 来检索内容,因此您也需要这样做require 'open-uri'。Nokogiri 读取 Open-URIopen返回的文件句柄。

本节可以写得更简洁:

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)
于 2012-09-17T16:41:27.517 回答