Ruby rspec共享_上下文,并包含所有规范的_上下文

Ruby rspec共享_上下文,并包含所有规范的_上下文,ruby,testing,rspec,Ruby,Testing,Rspec,我正试图定义一些let和before钩子,它们将通过使用 我试过这样的方法: module Helpers def self.included(base) base.let(:x){ "x" } base.before(:all){ puts "x: #{x}" } end end Rspec.configure{|c| c.include Helpers } 但这并不像预期的那样有效。(:all)之前的不仅在每个主要示例组之前运行,而且也在每个嵌套的示例组之前运行

我正试图定义一些
let
before
钩子,它们将通过使用

我试过这样的方法:

module Helpers
  def self.included(base)
    base.let(:x){ "x" }
    base.before(:all){ puts "x: #{x}" }
  end
end

Rspec.configure{|c| c.include Helpers }
但这并不像预期的那样有效。(:all)之前的
不仅在每个主要示例组之前运行,而且也在每个嵌套的示例组之前运行

然后我发现了,这似乎正是我想要的

然而,我的公开问题是,我不知道如何在我的所有规范中共享上下文。文档仅参考特定规范中的
包括上下文


有人能告诉我如何在全球范围内实现这种行为吗?我知道我可以在
spec\u helper
中定义global-before-hook,但我似乎不能使用
let
。我希望有一个地方可以同时定义这两个方面,并且不会污染我的spec helper,只需包含它即可。

我试图重现您的错误,但失败了

# 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

当我编写类似于
base.before(:all){p'global before';@blacks=10}
的东西时,我在spec输出中只得到了一行


请注意,我没有尝试在示例中修改实例变量,因为(实际上,如果是哈希或数组,您可以修改实例变量)。此外,即使将嵌套示例组中的
before(:all)
更改为
before(:each)
,每个示例中仍将有9个瓶子。

根据RSpec测试,
before(:all)
必须,无论它定义在何处。那么这可能是RSpec问题?不,我不认为这是RSpec问题。我不认为上面的代码是在配置中包含模块的预期用途。我非常确定模块将包含在每个示例组中,包括嵌套的示例组,因此我的
before(:all)
在每个示例组之前运行是有意义的。哦,很有趣。。。我使用的是旧版本的rspec,新版本只运行一次。。。也许我可以做我想做的!仍然有一些奇怪的事情在发生。我有一个
before(:all)
只做了一个
put
语句,它以无法解释的方式破坏了我的测试。在(:all)
之前取出
,一切都会正常工作。我仍然不认为使用这样的模块是我们想要的方法。我很确定我想要一个
共享的上下文
,只是不知道如何在全球范围内使用它。