Ruby 需要“文件”;和相对位置
所以我正在编写一些 rspec 测试,但我对自己缺乏 Ruby 理解感到尴尬。
我有一个如下所示的文件结构:
- GUI_Tests/Tests/test_spec.rb
- GUI_Tests/windows_gui.rb
- GUI_Tests/upload_tool.rb
当我为 test_spec.rb 文件运行规范时,我要求包含 upload_tool 文件,如下所示:
spec -r ../upload_tool -fs test_spec.rb
然后,upload_tool需要windows_gui.rb,如下所示:
require '../windows_gui'
我的问题是,为什么我必须引用相对于test_spec.rb的windows_gui.rb(需要../)而不是upload_tool.rb?这对我来说是错误的,我想在测试规范的上下文之外使用 upload_tool.rb,这意味着每次都更改需求。
显然我遗漏了一些东西,但是如果我没有相对于测试规范进行引用,我会收到文件未找到错误。
抱歉我在这里太无知了,但我是空手而归。任何想法表示赞赏。
BB
So I'm writing some rspec tests and I'm embarrassed at my lack of Ruby understanding.
I have a file structure that looks like the following:
- GUI_Tests/Tests/test_spec.rb
- GUI_Tests/windows_gui.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:
spec -r ../upload_tool -fs test_spec.rb
Then, the upload_tool requires windows_gui.rb, like so:
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? 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.
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你不知道。
require
是相对于当前目录的,在您的例子中是GUI_Tests/Tests
。如果你这样做:你将不得不使用这个:
解决该问题的最常见方法是使用 File.dirname(__FILE__):
注意:在 Ruby 1.9.2 中 require 更改了它的默认值: Ruby:require 与 require_relative - 最佳实践在 Ruby <1.9.2 和 >=1.9.2 中运行的解决方法
You don't.
require
s are relative to the current directory, which in your case wasGUI_Tests/Tests
. If you did this instead:You would have to use this:
The most common way to get around that problem is using
File.dirname(__FILE__)
: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