Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rspec and_return multiple values

I am trying to stub a method that returns multiple values. For example:

class Foo
  def foo(a,b)
    return a + 1, b + 2
  end
end

I want to stub it but I'm having trouble with and_return with 2 value returns

f = Foo.new
f.stub!(:foo).and_return(3,56)

doesn't work. It basically returns 3 the first time it's called and 56 the second time. Does anyone know what the syntax would be to have it return 3,56 the first time it's called? Is this even possible with rspec?

thanks in advance... jd

like image 876
jaydel Avatar asked Nov 08 '11 13:11

jaydel


People also ask

What is stub in RSpec?

In RSpec, a stub is often called a Method Stub, it's a special type of method that “stands in” for an existing method, or for a method that doesn't even exist yet.

How do I mock a method in RSpec?

Mocking with RSpec is done with the rspec-mocks gem. If you have rspec as a dependency in your Gemfile , you already have rspec-mocks available.

What is allow in RSpec?

Use the allow method with the receive matcher on a test double or a real. object to tell the object to return a value (or values) in response to a given. message. Nothing happens if the message is never received.

What is subject in RSpec?

Summary: RSpec's subject is a special variable that refers to the object being tested. Expectations can be set on it implicitly, which supports one-line examples. It is clear to the reader in some idiomatic cases, but is otherwise hard to understand and should be avoided.


1 Answers

Multiple-value returns are arrays:

> def f; return 1, 2; end
> f.class
 => Array 

So return an array:

f.stub!(:foo).and_return([3, 56])
like image 61
Dave Newton Avatar answered Nov 15 '22 06:11

Dave Newton