1

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?

Vega
  • 27,856
  • 27
  • 95
  • 103
alkalinecoffee
  • 1,003
  • 8
  • 20
  • Depends on what is in the method but you could test what is left in `some_method` rather than testing `some_method` itself. – oldergod Feb 12 '13 at 13:56

1 Answers1

1

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
Matt Gibson
  • 14,616
  • 7
  • 47
  • 79
  • Yes, super is definitely being used in the real world. Essentially, `Automobile` sets up the data structure, and `Car` and `CompactCar` do the work on that structure. I originally didn't want to pull out the code specific for `CompactCar`, but I just may have to do that. – alkalinecoffee Feb 12 '13 at 14:48
  • In that case, I'd mock/stub to simulate the effect of super rather than depend upon it. Then test super separately. – Matt Gibson Feb 12 '13 at 16:43