3

I have a function func that returns an array with two arguments which I normally use as follows:

heads, tails = func

so in an rspec test, I would like to write

let(:heads, :tails, :draw){ func }

but this raises an exception. I know I can just put

let(:ans){ func }
let(:heads){ ans.first }
let(:tails){ ans.second }

Is there an easier way to do this in rspec. If not, is there a method call that I can write that do this for me e.g.

def let_multi(f)
    let(:ans){ f }
    let(:heads){ ans.first }
    let(:tails){ ans.second }
end

and then in the test

let_multi func

My attempt with let_multi func does not work because func is only defined in an it block.

1 Answer 1

3

What you're describing can't be done. Let blocks are evaluated outside of the it block context and need to be setup prior to that.

Even the rspec error output suggests as much when you try to dynamically define the let:

let is not available from within an example (e.g. an it block) or from constructs that run in the scope of an example (e.g. before, let, etc). It is only available on an example group (e.g. a describe or context block).

This is because let blocks actually define a method that match the symbol given to the let, which is then lazily evaluated. As such it would need to be a new feature of rspec to allow for this type of array based initialization.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.