To achieve this, you can use before(:context) hook:
describe HeavyComputation, 'what I want ideally' do before(:context) { @result = described_class.new.compute_result } subject { @result } it { should include 'big' } it { should match 'string' } it { should match /very/ }
Remember that before(:context) contains a number of caveats:
Warning: before(:context)
It is very tempting to use before(:context) to speed up the process, but we recommend that you avoid this, as there are a number of errors. like things that just don't work.
Context
before(:context) run in the example that is created to provide the group context for the block.
instance variables
Instance variables declared in before(:context) are shared across all the examples in the group. This means that each example can change the state of a common object, which leads to an order dependency, which can make it difficult to talk about failures.
unsupported rspec constructs
RSpec has several constructs that reset define between each example automatically. They are not intended to be used from before(:context) :
let adssubject ads- Any mocking, sealing, or testing double ads
other frameworks
Object mockups and database transaction managers (such as ActiveRecord) are typically designed around the idea of ββcreating before an example, by running this one example and then breaking it down. This means that layouts and stubs can (sometimes) be declared in before(:context) , but come off before the first real example works.
You can create model objects with database support in before(:context) in rspec-rails, but it will not wrap the transaction for you, so you yourself can clear the after(:context) block.
(from http://rubydoc.info/gems/rspec-core/RSpec/Core/Hooks:before )
As long as you understand that your before(:context) hook is outside the normal life cycle of every example of things like double tests and database transactions, and you explicitly manage the necessary settings and disconnections yourself, you'll be fine, but others who work on your code base may not be aware of these errors.