如何在 RSpec 2 中自动加载 spec_helper.rb [英] How to load a spec_helper.rb automatically in RSpec 2
问题描述
在 Ruby 中开发 gems 时,我几乎总是需要一个文件,我可以在其中配置 RSpec 以满足我的需要,也许在此之前,需要一些帮助模块,这些模块应该在我的所有 spec
示例中可用.
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.
在 Rails 应用程序中,使用名为 spec/spec_helper.rb
的文件.令我烦恼的一件事是,在典型的 Rails 环境中,您必须在每个包含要加载的示例的文件中都需要这个 spec_helper.rb 文件.过去,我遇到了很多与更改示例文件中的加载路径和相关需求路径相关的问题.
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.
现在对于我的 gems,我希望有一种方法可以在加载任何示例文件之前只说 RSpec 需要 spec_helper.rb 文件.如果我调用 rspec 可执行文件,或者我可以在我的 Rakefile 中定义的 rake spec 任务,这与事实无关.
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.
我知道我只能告诉 RSpec 我的 spec_helper.rb 的位置是这个 spec_helper.rb 需要手动所有示例文件,但我也想避免这种方法的额外维护.
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?
推荐答案
在 RSpec 2 中,/spec
文件夹总是自动在你的加载路径上.这意味着您只需要:
In RSpec 2, the /spec
folder is always automatically on your load path. This means that all you need is:
require 'spec_helper'
在规范文件的顶部.这将始终加载 /spec/spec_helper.rb
,并且是您能够逃脱的最低限度.
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:
require File.join(File.dirname(File.dirname(__FILE__)), 'spec_helper.rb')
(需要针对不同的嵌套级别进行更新).
(which needs to be updated for different nesting levels).
你也可以在你的 .rspec
文件中添加选项:--require spec_helper
,这将在每个规范文件中需要这个文件,没有手动的 require 语句顶部.
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 2 中自动加载 spec_helper.rb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!