如何在 RSpec 2 中自动加载spec_helper.rb
在 Ruby 中开发 gem 时,我几乎总是需要一个文件,可以在其中根据我的需要配置 RSpec,也许在这样做之前,需要一些辅助模块,这些模块应该在我的所有 spec
示例中可用。
在 Rails 应用程序中,使用名为 spec/spec_helper.rb
的文件来实现此目的。让我烦恼的一件事是,在典型的 Rails 环境中,您必须在每个包含示例的文件中都需要此 spec_helper.rb 文件才能加载。过去,我遇到了很多与更改示例文件内的加载路径和相对需求路径相关的问题。
现在对于我的 gems,我希望有一种方法可以让 RSpec 在加载任何示例文件之前需要 spec_helper.rb 文件。与我调用 rspec 可执行文件或我可以在 Rakefile 中定义的 rake spec 任务无关。
我知道我只能告诉 RSpec 我的spec_helper.rb 的位置,这个spec_helper.rb 需要手动提供所有示例文件,但我也想避免这种方法的额外维护。
有更好的方法来实现这一点吗?
When developing gems in Ruby, I almost always need a file in which I can configure RSpec to my needs and maybe before doing that, require some helper modules which should be available in all my spec
examples.
In Rails applications a file named spec/spec_helper.rb
is used for that. One thing that annoys me is that in the typical Rails environment, you have to require this spec_helper.rb file in every file that contains examples for it to be loaded. In the past I had a lot of problems with this related to changing load paths and relative require paths inside the example files.
Now for my gems, I would wish to have a way to just say RSpec to require the spec_helper.rb file before loading any of the examples files. Independent of the fact if I call rspec executable, or the rake spec task which I may define in my Rakefile.
I know I can tell RSpec only the location of my spec_helper.rb is this spec_helper.rb requires all the example files manually, but I would also like to avoid the additional maintenance of that approach.
Is there a nicer way to accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 RSpec 2 中,
/spec
文件夹始终自动位于您的加载路径上。这意味着您所需要的只是:位于规范文件的顶部。这将始终加载
/spec/spec_helper.rb
,并且是您能够逃脱的最小值。这意味着您不需要诸如以下的可怕方法:(
需要针对不同的嵌套级别进行更新)。
您还可以在
.rspec
文件中添加选项:--require spec_helper
,这将在每个规范文件中需要此文件,而无需在顶部手动 require 语句。In RSpec 2, the
/spec
folder is always automatically on your load path. This means that all you need is:at the top of your spec files. This will always load
/spec/spec_helper.rb
, and is the minimum you'll be able to get away with.This means you don't need a horrid approach such as:
(which needs to be updated for different nesting levels).
Also you can add to your
.rspec
file the option:--require spec_helper
, which will require this file in each spec file, without the manual require statement at the top.当您执行
rspec --init
时,--require spec_helper
行会自动添加到 RSpec 3.0 的 .rspec 文件中。The
--require spec_helper
line is automatically added to the .rspec file for RSpec 3.0 when you dorspec --init
.