How do I store a variable in rspec?
I have something along the following lines in one of my files spec
:
expect(my_instance).to receive(:my_function).with(arg: instance_of(String))
I want to be able to capture the actual value arg
in a variable that I can use in a spec. Is there a way to do this? I checked the rspec docs but couldn't find anything similar.
source to share
You can declare a variable, say captured_arg
, before expect
(or allow
if you don't want it to fail if it my_instance
doesn't receive my_function
). Then you can collect the arguments in a block and set captured_arg
inside that block.
captured_arg = nil
expect(my_instance).to receive(:my_function) { |arg| captured_arg = arg }
Edit: (Keyword Arguments)
If you are using keyword arguments , slightly modify the script above using arg
as keyword argument, how to capture:
captured_arg = nil
expect(my_instance).to receive(:my_function) { |args| captured_arg = args[:arg] }
source to share