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
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.
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.
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.
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.
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With