rubyrspec3

How to mock my superclass in rspec


I have the following code:

class Blurk
  def initialize
    # horror
  end

  def perform
    # yet more horror
  end
end

class Grunf < Blurk
   def perform
     super
     # here some code to test
   end
end

I would like to test the code on Grunf#perform but I can't figure out how to mock Blurk.


Solution

  • In general you shouldn't do it. A better approach (IMHO) is to make some slight changes to your class definitions

    class Blurk
      def initialize
        # horror
      end
    
      def perform
        # yet more horror
        exec_perform
      end
      
      protected
      
      def exec_perform
        raise "exec_perform must be overriden"
      end
    end
    
    class Grunf < Blurk
       def exec_perform
         # here some code to test
       end
    end
    

    and to test Blurk and Grunf separately (in Blurk tests you may create TestClass definition in order to confirm exec_perform is run as expected). In Grunf's test file you would just test the exec_perform method.