How do you mock an object that you don't have access to?

Hi,

How can I mock the “go” method of class B so that it returns the
string “fudge” in this situation?

class A
private
def start
@b = B.new
end
end

class B
def go
puts “This is fun.”
end
end

Also, is it possible to do the mocha-like any_instance thing with RSpec?

Thank you,
David :slight_smile:

On Fri, Mar 28, 2008 at 3:25 PM, David B.
[email protected] wrote:

end

class B
def go
puts “This is fun.”
end
end

What about:

mock_b = mock(B)
mock_b.stub!(:go).and_return(true)

B.stub!(:new).and_return(mock_b)

Something like that?


Luis L.
Multimedia systems

Human beings, who are almost unique in having the ability to learn from
the experience of others, are also remarkable for their apparent
disinclination to do so.
Douglas Adams

On Fri, Mar 28, 2008 at 11:32 AM, Luis L. [email protected]
wrote:

end

mock_b = mock(B)
mock_b.stub!(:go).and_return(true)

B.stub!(:new).and_return(mock_b)

Something like that?

Stubbing the #new method on the class is one way to do it, as Luis
mentioned.

Another approach is to pass the object in through the constructor.
Doing so will help you achieve looser coupling between the classes.

Pat

http://atomicobjectrb.rubyforge.org/injection/

Zach

On Fri, Mar 28, 2008 at 2:17 PM, aslak hellesoy

Awesome. Thank you.

David :slight_smile:

On Fri, Mar 28, 2008 at 8:12 PM, Pat M. [email protected] wrote:

@b = B.new

What about:
Another approach is to pass the object in through the constructor.
Doing so will help you achieve looser coupling between the classes.

AKA Dependency Injection
(http://martinfowler.com/articles/injection.html)

Aslak

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs