类方法覆盖

class Object
  def mock(mock)
    original = self
    klass = Class.new(self) do
      instance_eval do
        mock.each do |method, proc|
          define_method("mocked_#{method}", &proc)
          alias_method method, "mocked_#{method}"
        end
      end
    end
    begin
      Object.send(:remove_const, self.name.to_s)
      Object.const_set(self.name.intern, klass)
      yield
    ensure
      Object.send(:remove_const, self.name.to_s)
      Object.const_set(self.name.intern, original)
    end
  end
end

class Duck
  def quak
    puts "Quak"
  end
end

Duck.new.quak  # => "Quak"

Duck.mock(:quak => Proc.new { puts 'Wuff' }) do
  Duck.new.quak  # => "Wuff"
end

 

你可能感兴趣的:(方法)