Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically share context in RSpec

Tags:

ruby

rspec

I want to share a memoized method between my specs. So I tried to use shared context like this

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

describe 'something' do
  include_context :specs
end

It works ok. But I have about 60 spec files, so I'm forced to explicitly include context in each of them. Is there an way to automatically include shared context (or at least let definition) for all example groups in spec_helper.rb?

Something like this

RSpec.configure do |spec|
  spec.include_context :specs
end
like image 810
p0deje Avatar asked Jul 01 '12 14:07

p0deje


People also ask

What is shared context in RSpec?

Shared Contexts in RSpec In RSpec, every example runs in a context: data and configuration for the example to draw on, including lifecycle hooks, let and subject declarations, and helper methods. These contexts are inherited (and can be overridden) by nested example groups.

How do you use shared context?

We use shared context to reuse an inital state of the test that different sets of assertions can use later. To declare a shared context you need two keywords: Use shared_context and pass a block to declare the context. Use include_context to include the context in a block.

What is shared examples in RSpec?

Shared examples are a good tool to describe some complex behavior and reuse it across different parts of a spec. Things get more complicated when you have the same behavior, but it has some slight variations for different contexts.

What is shared context?

Definition 20.1. Shared context occurs when people or people and machines collaboratively and interactively solve problems. Shared context contains knowledge about the problem at hand and background and common-sense knowledge.


1 Answers

You can set up global before hooks using RSpec.configure via configure-class-methods and Configuration:

RSpec.configure {|c| c.before(:all) { do_stuff }}

let is not supported in RSpec.configure, but you can set up a global let by including it in a SharedContext module and including that module using config.before:

module MyLetDeclarations
  extend RSpec::Core::SharedContext
  let(:foo) { Foo.new }
end
RSpec.configure { |c| c.include MyLetDeclarations }
like image 112
Jeremy Peterson Avatar answered Oct 19 '22 06:10

Jeremy Peterson