简体   繁体   中英

Stubbing a method that returns multiple values rspec

Consider the following function that returns two values (let's say it's a method associated with a class Foo ):

def returns_two_things()
// some logic that computes result1 and result 2
return result1, result2
end

I thought I could stub returns_two_things like this:

allow(@my_foo_instance).to receive(:returns_two_things) \
  .and_return("foo", "bar")

But only "foo" is being returned. I gather that the and_return method is used to tell rspec to return "foo" the first time returns_two_things is called and "bar" the second time. This is how I'm invoking returns_two_things in the code I'm trying to test

result1, result2 = @my_foo_instance.returns_two_things()

How can I get rspec to return two values from the stubbed function?

Ruby does not have multivalue returns. The code example provided implicitly returns an array with 2 elements, ie return "foo", "bar" is same as return ["foo", "bar"] .

So the correct way to stub is:

allow(@my_foo_instance).to receive(:returns_two_things) \
  .and_return(["foo", "bar"])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM