CaseyJones CaseyJones - 2 months ago 13
Ruby Question

rspec stubbing passing the same arguments

Sample code:

class Foo
def initialize(abc)
@abc = abc
@bind = bar
end
def bar
SomeClass.new(@abc)
end
end


Now I want to stub bar using rspec and custom stub:

allow('Foo').to receive(:bar).and_return(FakeBar.new)


The issue is that the
FakeBar.new
has to be initialize with the same arguments
:bar
receives. Is it possible to get a copy of params passed to
:bar
at the time we are stubbing and reuse them in the stub class?

Answer

Not sure why you want to do what you're doing (probably there is a simpler way), but for what it's worth:

allow("Foo").to receive(:bar) { |arg1, arg2| FakeBar.new(arg1, arg2) }

RSpec docs, block stub implementation