Reputation: 16393
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.
Upvotes: 3
Views: 3892
Reputation: 43855
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. anit
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. adescribe
orcontext
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.
Upvotes: 3