Annoying fact of the day. Stubbing delegates
A possibly dangerous habit I’ve taken up lately is using Delegate in ruby as a way of changing the behaviour of a nasty dependency that’s just too prevalent in the system to break.
(The possibly dangerous part is that I’m still leaving dependencies hanging around that I know should be broken now, but oh well.)
Noticed something today that took me a long time to track down: methods that have been overridden by the delegating class, can’t be stubbed simply with instance.stub!(:method), as the stub! method gets proxied to the underlying delegate and the overriding method in the delegator is left as is.
Update: The code I ended up using instead of a Delegate in this case
module ConnectionProxies
class ConnectionProxy
def initialize(obj)
@connection = obj
end
#proxy all of these methods straight to the underlying connection
[
:create_table,
:transaction,
:quote,
:execute,
:native_database_types,
:adapter_name,
:table_exists?,
:columns
].each do |method|
define_method(method) do |*args,&block|
@connection.send(method,*args,&block)
end
end
end
end