Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using meck to make multiple calls to the same method with the same arguments

Tags:

erlang

eunit

meck

I know that with ruby/rspec, you can do something like the following in order to receive different return values for the different calls made to the method:

allow(double).to receive(:msg).and_return(value1, value2, value3)

I've only been able to make meck stub a method with one return value like so:

meck:expect(module, some_method, fun() -> ok end)

Is there a way to make it return ok on the first call and then ok2 on the second?

like image 694
Tony Baik Avatar asked Dec 15 '22 13:12

Tony Baik


2 Answers

To do this, there are two shortcuts in Meck you can use:

  • meck:sequence/4 This function returns each element in a sequence, until the last element. Then, the last element is returned indefinitely.

    6> meck:sequence(module, some_method, 0, [ok, ok2]).
    ok
    7> module:some_method().
    ok
    8> module:some_method().
    ok2
    9> module:some_method().
    ok2
    
  • meck:loop/4 This function returns each element in a loop. When the last element is returned, it starts over with the first.

    10> meck:loop(module, some_method, 0, [ok, ok2]).
    ok
    11> module:some_method().
    ok
    12> module:some_method().
    ok2
    13> module:some_method().
    ok
    
like image 111
Adam Lindberg Avatar answered Apr 27 '23 17:04

Adam Lindberg


You can do this by redefining the expectaction function the first time it's called:

meck:expect(module,
            some_method, 
            fun() ->
                     %% Redefine the expect fun for next invocation
                     meck:expect(module,
                                 some_method,
                                 fun() ->
                                          ok2 
                                 end),
                     ok
            end).
like image 26
johlo Avatar answered Apr 27 '23 17:04

johlo