在RSpec中自动共享上下文

p0d*_*eje 15 ruby rspec

我想在我的规范之间分享一个memoized方法.所以我尝试使用像这样的共享上下文

RSpec.configure do |spec|
  spec.shared_context :specs do
    let(:response) { request.execute! }
  end
end

describe 'something' do
  include_context :specs
end
Run Code Online (Sandbox Code Playgroud)

它工作正常.但我有大约60个spec文件,所以我不得不明确地在每个文件中包含上下文.有没有办法自动包含let所有示例组的共享上下文(或至少定义)spec_helper.rb

像这样的东西

RSpec.configure do |spec|
  spec.include_context :specs
end
Run Code Online (Sandbox Code Playgroud)

小智 29

您可以before使用RSpec.configurevia configure-class-methodsConfiguration设置全局挂钩:

RSpec.configure {|c| c.before(:all) { do_stuff }}
Run Code Online (Sandbox Code Playgroud)

let不受支持RSpec.configure,但您可以let通过将其包含在SharedContext模块中并使用config.before以下命令包含该模块来设置全局:

module MyLetDeclarations
  extend RSpec::Core::SharedContext
  let(:foo) { Foo.new }
end
RSpec.configure { |c| c.include MyLetDeclarations }
Run Code Online (Sandbox Code Playgroud)

  • 对于任何使用RSpec 3的人来说,它看起来像`RSpec :: Core :: SharedContext`已经消失,并被`RSpec :: SharedContext`取代. (12认同)

thr*_*onk 5

你可以做到这一点几乎像:有针对包括模块机制,并纳入模块都有自己的回调机制.

例如,假设我们有一个disconnected共享上下文,我们希望在没有数据库连接的情况下运行我们的所有模型规范.

shared_context "disconnected"  do
  before :all do
    ActiveRecord::Base.establish_connection(adapter: :nulldb)
  end

  after :all do
    ActiveRecord::Base.establish_connection(:test)
  end
end
Run Code Online (Sandbox Code Playgroud)

您现在可以创建一个包含该上下文的模块.

module Disconnected
  def self.included(scope)
    scope.include_context "disconnected"
  end
end
Run Code Online (Sandbox Code Playgroud)

最后,您可以以正常方式将该模块包含在所有规范中(我已经演示了仅针对模型执行此操作,只是为了表明您可以),这几乎就是您所要求的.

RSpec.configure do |config|
  config.include Disconnected, type: :model
end
Run Code Online (Sandbox Code Playgroud)

这适用于rspec-core2.13.0和rspec-rails2.13.0.


Tho*_*emm 5

在RSpec 3+中,这可以通过以下方式实现 - 基于Jeremy Peterson的回答.

# spec/supprt/users.rb
module SpecUsers
  extend RSpec::SharedContext

  let(:admin_user) do
    create(:user, email: 'admin@example.org')
  end
end

RSpec.configure do |config|
  config.include SpecUsers
end
Run Code Online (Sandbox Code Playgroud)