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
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.
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.
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.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With