简体   繁体   English

Ruby需要'文件'和相对位置

[英]Ruby require 'file' and relative location

So I'm writing some rspec tests and I'm embarrassed at my lack of Ruby understanding. 所以我正在写一些rspec测试,我对我缺乏Ruby理解感到尴尬。

I have a file structure that looks like the following: 我有一个如下所示的文件结构:

  • GUI_Tests/Tests/test_spec.rb GUI_Tests /测试/ test_spec.rb
  • GUI_Tests/windows_gui.rb GUI_Tests / windows_gui.rb
  • GUI_Tests/upload_tool.rb GUI_Tests / upload_tool.rb

when I run spec for the test_spec.rb file, I require the upload_tool file to be included like so: 当我运行test_spec.rb文件的规范时,我要求包含upload_tool文件,如下所示:

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

Then, the upload_tool requires windows_gui.rb, like so: 然后,upload_tool需要windows_gui.rb,如下所示:

require '../windows_gui'

My question is, why so I have to reference windows_gui.rb relative to test_spec.rb (requiring the ../) rather than the upload_tool.rb? 我的问题是,为什么我必须引用相对于test_spec.rb(需要../)而不是upload_tool.rb的windows_gui.rb? This feels wrong to me, I'll want to use the upload_tool.rb out of context of the test specs, which means changing the requires each time. 这对我来说是错误的,我想在测试规范的上下文中使用upload_tool.rb,这意味着每次都要更改要求。

Clearly I'm missing something, but if I don't reference relative to the test spec I get a file not found error. 显然我遗漏了一些东西,但是如果我没有引用相对于测试规范,我得到一个文件未找到错误。

Sorry for being so ignorant here, but I'm coming up empty handed. 很抱歉在这里这么无知,但我空手而归。 Any thoughts appreciated. 任何想法都赞赏。

BB BB

You don't. 你没有。 require s are relative to the current directory, which in your case was GUI_Tests/Tests . require s是相对于当前目录的,在您的情况下是GUI_Tests/Tests If you did this instead: 如果你这样做了:

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

You would have to use this: 你必须使用这个:

require 'windows_gui' # without '../'

The most common way to get around that problem is using File.dirname(__FILE__) : 解决该问题的最常见方法是使用File.dirname(__FILE__)

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

NOTE: in Ruby 1.9.2 require changed it's defaults: Ruby: require vs require_relative - best practice to workaround running in both Ruby <1.9.2 and >=1.9.2 注意:在Ruby 1.9.2中需要更改它的默认值: Ruby:require vs require_relative - 在Ruby <1.9.2和> = 1.9.2中运行的解决方法的最佳实践

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM