How can I mock super in ruby using rspec?

John Micalo picture John Micalo · Apr 6, 2013 · Viewed 9.2k times · Source

I am extending an existing library by creating a child class which extends to the library class.

In the child class, I was able to test most of functionality in initialize method, but was not able to mock super call. The child class looks like something like below.

class Child < SomeLibrary
    def initialize(arg)
        validate_arg(arg)
        do_something
        super(arg)
    end

    def validate_arg(arg)
        # do the validation
    end

    def do_something
        @setup = true
    end
end

How can I write rspec test (with mocha) such that I can mock super call? Note that I am testing functionality of initialize method in the Child class. Do I have to create separate code path which does not call super when it is provided with extra argument?

Answer

Myron Marston picture Myron Marston · Apr 7, 2013

You can't mock super, and you shouldn't. When you mock something, you are verifying that a particular message is received, and super is not a message -- it's a keyword.

Instead, figure out what behavior of this class will change if the super call is missing, and write an example that exercises and verifies that behavior.