Search code examples
rubyruby-mocha

How do I bypass a call to super method in test


I have a basic structure like this

class Automobile
  def some_method
    # this code sets up structure for child classes... I want to test this
  end
end

class Car < Automobile
  def some_method
    super
    # code specific to Car... it's tested elsewhere so I don't want to test this now
  end
end

class CompactCar < Car
  def some_method
    super
    # code specific to CompactCar... I want to test this
  end
end

What is the recommended way to test CompactCar and Automobile without running the code from Car? Automobile#some_method provides the structure that is required by child classes, so I want to always test that, but Car's functionality is tested elsewhere and I don't want to duplicate efforts.

One solution is to use class_eval to overwrite Car#some_method, but this isn't ideal because the overwritten method stays in place for the duration of my testing (unless I re-load the original library file with setup/teardown methods... kind of an ugly solution). Also, simply stubbing the call to Car#some_method does not seem to work.

Is there a cleaner/more generally accepted way of doing this?


Solution

  • Just put the specific code into a separate method. You don't appear to be using anything from super. Unless you are?

    class CompactCar < Car
      def some_method
        super
        compact_car_specific_code
      end
    
      # Test this method in isolation.
      def compact_car_specific_code
        # code specific to CompactCar... I want to test this
      end
    end