This will call the belongs_to method on the class that the module is
included in. You may need to fiddle with the syntax, can't test this
at the moment.
I am trying to do a functional test on a controller that mixes in a module with an expensive method, but I would like to mock out that method for my testing purposes. I can't seem to do it. Here's what I have tried
def setup
@controller = MyController.new
klass = class << @controller; self; end
klass.send(:undef_method, :something_expensive)
klass.send(:define_method, :something_expensive, lambda {nil})
end
I have also tried to do the less idiomatic but more straightforward
def @controller.something_expensive; nil; end
but that didn't help, either. The undef_method fails because it can't find the method (I guess becaues it's actually defined in the module). The other way just silently fails to accomplish its objective. I've googled some but am somewhat perplexed. Ideas?
### this is what the controller looks like ###
class MyController
include ModuleWithExpensiveMethod
end
module ModuleWithExpensiveMethod
def something_expensive
sleep(100)
end
end
Both of these techniques work fine when I try your examples - are you sure your example illustrates the problem you are seeing?
A third way is like this…
def setup
@controller = MyController.new
class << @controller
undef something_expensive # not strictly necessary
def something_expensive; end
end
end
But if you are getting into mocking and stubbing, you might like to have a look at Mocha at
http://mocha.rubyforge.org which can make your life a bit easier.