代码之家  ›  专栏  ›  技术社区  ›  Bobby B

Ruby需要'file'和相对位置

  •  19
  • Bobby B  · 技术社区  · 15 年前

    我的文件结构如下所示:

    • GUI测试/测试/测试规范rb
    • GUI测试/上传工具.rb

    spec -r ../upload_tool -fs test_spec.rb
    

    然后,upload\u工具需要windows\u gui.rb,如下所示:

    require '../windows_gui'
    

    很明显我遗漏了一些东西,但是如果我不引用测试规范,我会得到一个filenotfound错误。

    很抱歉我在这里这么无知,但我空手而来。有什么想法我都很感激。

    1 回复  |  直到 12 年前
        1
  •  20
  •   Community CDub    8 年前

    你没有。 require 是相对于当前目录的,在您的例子中是 GUI_Tests/Tests

    cd ..
    spec -r upload_tool -fs Test/test_spec.rb
    

    您必须使用:

    require 'windows_gui' # without '../'
    

    解决这个问题最常见的方法是使用 File.dirname(__FILE__)

    require File.join(File.dirname(__FILE__), '..', 'windows_gui')
    

    注意:在Ruby 1.9.2中,需要更改它的默认值: Ruby: require vs require_relative - best practice to workaround running in both Ruby <1.9.2 and >=1.9.2