问题描述
我正在尝试定义一些 let
和 before
钩子,通过使用 Rspec 配置块.
I'm trying to define a few let
's and before
hooks that will run globally for all my specs by including them in a separate file using the Rspec configuration block.
我尝试了类似的东西:
module Helpers
def self.included(base)
base.let(:x){ "x" }
base.before(:all){ puts "x: #{x}" }
end
end
Rspec.configure{|c| c.include Helpers }
但这并不像预期的那样工作.before(:all)
不仅在每个主要示例组之前运行,而且还运行在每个嵌套组之前.
but this doesn't work as expected. The before(:all)
doesn't just run before each main example group, but each nested one as well.
然后我发现了 shared_context它似乎正是我想要的.
Then I found out about shared_context and it appears to be exactly what I want.
然而,我的开放性问题是我无法弄清楚如何在我的ALL 规范之间共享上下文.文档仅在特定规范中引用了 include_context
.
My open problem however is that I can't figure out how to share a context amongst ALL of my specs. The docs only reference include_context
within a specific spec.
谁能告诉我如何以全局方式实现这种行为?我知道我可以在我的 spec_helper
中定义 global before 钩子,但我似乎无法使用 let
.我想要一个地方,我可以定义这两个东西并且不会污染我的规范助手,而只是包含它.
Can anyone tell me how I can achieve this behavior in a global manner? I'm aware that I can define global before hooks in my spec_helper
but I can't seem to use let
. I'd like a single place that I can define both of these things and not pollute my spec helper, but just include it instead.
推荐答案
我试图重现您的错误,但失败了.
I tried to reproduce your error, but failed.
# spec_helper.rb
require 'support/global_helpers'
RSpec.configure do |config|
config.include MyApp::GlobalHelpers
end
# support/global_helpers.rb
module MyApp
module GlobalHelpers
def self.included(base)
base.let(:beer) { :good }
base.before(:all) { @bottles = 10 }
end
end
end
# beer_spec.rb
require 'spec_helper'
describe "Brewery" do
it "makes good stuff" do
beer.should be :good
end
it "makes not too much bottles" do
@bottles.should == 10
end
context "when tasting beer" do
before(:all) do
@bottles -= 1
end
it "still produces good stuff" do
beer.should be :good
end
it "spends some beer on degusting" do
@bottles.should == 9
end
end
end
https://gist.github.com/2283634
当我写类似 base.before(:all) { p 'global before';@bottles = 10 }
,我在规范输出中只有一行.
When I wrote something like base.before(:all) { p 'global before'; @bottles = 10 }
, I got exactly one line in spec output.
请注意,我没有尝试修改示例中的实例变量,因为 无论如何都行不通(好吧,实际上你可以修改实例变量,如果它是一个散列或数组).而且,即使将嵌套示例组中的before(:all)
改为before(:each)
,每个示例中仍然有9个瓶子.
Notice that I didn't try to modify instance variables inside an example, because it wouldn't work anyway (well, actually you can modify instance variables, if it's a hash or array). Moreover, even if you change before(:all)
in nested example group to before(:each)
, there will be still 9 bottles in each example.
这篇关于rspec shared_context 和 include_context 适用于所有规范的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!