How to mock a model method for unit tests?

I have a model class, say, model.rb, and in the normal course of things
it creates an instance of another class, say utility.rb (also in the
models directory).

class Utility

def initialize(obj)
# do stuff…
end

def do_something_expensive
# lots of stuff here
end

end

During testing, I want to mock out do_something_expensive because it’s
not important for the tests, but only during development. So I went to
the tests\mocks folder and added a file called utility.rb with only
this:

this is the mock file

class Utility

def do_something_expensive
# shortcut, just return true to satisfy client code
true
end

end

So this way, in my tests, when my model uses the Utility class, it
should be insantiating my mock instead.

But when I rake test:units, I get a syntax error saying that it can’t
construct a Utility object with the original constructor: “Wrong number
of argumes (0 for 1)”.

It’s as if the mock class is totally taking over, whereas I just want to
override the do_something_expensive and leave everything else.

What am I doing wrong?

The Utility class is actually larger than I’m showing here, and I’m
finding I have to basically copy all of the methods into the mock to get
it to work.

Jeff

Jeff C. wrote:

But when I rake test:units, I get a syntax error saying that it can’t
construct a Utility object with the original constructor: “Wrong number
of argumes (0 for 1)”.

It’s as if the mock class is totally taking over, whereas I just want to
override the do_something_expensive and leave everything else.

What am I doing wrong?

You need to require the original class so that you’re re-opening it, as
opposed to redefining it from scratch. Then you can knock out the one
unwanted function, while leaving all the others intack

Eric

On Thursday, June 15, 2006, at 5:42 PM, Eric D. Nielsen wrote:

You need to require the original class so that you’re re-opening it, as
http://lists.rubyonrails.org/mailman/listinfo/rails
you should also put the mocks in the ‘test/mock/development’ or ‘test/
mock/test’ if you want it to only load during development or testing.

_Kevin

On Thursday, June 15, 2006, at 5:42 PM, Eric D. Nielsen wrote:

You need to require the original class so that you’re re-opening it, as
http://lists.rubyonrails.org/mailman/listinfo/rails

Doh!! Thanks a lot, Eric.

Kevin O. wrote:

you should also put the mocks in the ‘test/mock/development’ or ‘test/
mock/test’ if you want it to only load during development or testing.

_Kevin

Yes, I forgot to say that I did put it in the test/ folder, but thanks
for pointing that out.

Jeff