测试宝石时需要错误

时间:2013-05-23 00:00:13

标签: ruby rubygems gem

我有一个项目树如下:

├── bin
├── fpgrowth-ruby-0.0.1.gem
├── fpgrowth-ruby.gemspec
├── Gemfile
├── Gemfile.lock
├── lib
│   ├── fpgrowth
│   │   ├── fptree
│   │   │   ├── builder
│   │   │   │   ├── first_pass.rb
│   │   │   │   └── second_pass.rb
│   │   │   ├── fp_tree.rb
│   │   │   └── node.rb
│   │   ├── models
│   │   │   └── transaction.rb
│   │   └── ruby
│   │       └── version.rb
│   └── fpgrowth.rb
├── LICENSE.txt
├── Rakefile
├── README.md
└── test
    └── tc_first_pass.rb

在first_pass的测试用例中,我写道:

require 'test/unit'
require "../lib/fpgrowth/fptree/builder/first_pass"

然后我明白了:

ruby test/tc_first_pass.rb 
/home/damien/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot load such file -- ../lib/fpgrowth/fptree/builder/first_pass (LoadError)
    from /home/damien/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from test/tc_first_pass.rb:2:in `<main>'

出了点问题,但我不知道是什么。

3 个答案:

答案 0 :(得分:1)

除非您使用require_relative,否则不能要求此类文件。

除此之外,您应该更改$LOAD_PATH以包含../lib

答案 1 :(得分:1)

在ruby命令行上使用-I标志,以在运行时指定require路径。

来自您的顶级目录

ruby -I lib test/tc_first_pass.rb

上面告诉ruby解释器只在这个执行的加载路径中包含/ lib。

然后是你的需求行,

require 'fpgrowth/fptree/builder/first_pass'

对于宝石构建和组织您的源代码,我建议您阅读有关组织源代码的章节,以及从此处的Programming Ruby书籍中分发和打包您的代码:http://pragprog.com/book/ruby3/programming-ruby-1-9

答案 2 :(得分:0)

您可以使用File类方法来帮助您。

首先是从不相对于cwd的目录开始,而是相对于调用require的文件。它们可能不一样。

require File.dirname(__FILE__) + "../lib/fpgrowth/fptree/builder/first_pass"

然而,这不是非常便携,可以使用join类方法进行清理:

require File.join(File.dirname(__FILE__), '..', 'lib', 'fpgrowth', 'fptree', 'builder', 'first_pass')

但是你可能发现自己在这个地方添加了这个,不是吗?在这种情况下,请考虑在fpgrowth.rb中添加帮助:

def self.root
  Pathname.new(File.expand_path(File.dirname(__FILE__)))
end

现在,您可以在整个地方使用该助手:

FpGrowth.root #=> "/absolute/path/to/fpgrowth/lib"
FpGrowth.root.join("fpgrowth", "fbtree", "builder") #=> "/absolute/path/to/fpgrowth/lib/fpbrowth/fbtree/builder"
相关问题