Mocking Kernel Methods with RSpec

Sometimes you might want to set message expectations on the Kernel Module methods like open, puts, etc (more). Trying to mock Kernel.open i found out that the message expectation fails to catch the call to the method when you set the expectation as:

Kernel.should_receive(:open)

So, after a little searching, i realized that when you call Kernel methods from within a class, you can mock the method you want to call directly in the class, as in:

class MyTestClass
  def say_hi
    puts "Hi!"
  end
end
# Expectations
describe MyTestClass do
  describe "#say_hi" do
    subject { MyTestClass.new }
    it "should say hi" do
      subject.should_receive(:puts).with("Hi!")
      subject.say_hi
    end
  end
end

When you call puts from within the class Test, self is set to the object itself, and it acts as the receiver for puts. If you don’t implement puts, the interpreter goes up the class chain looking for the method until it finds it in Object, that mixes in the Kernel module!

  • rosic

    Hi,
    wasn’t :
    subject { Test.new }
    meant to be:
    subject { MyTestClass.new }
    ?

    • http://rubynoobie.wordpress.com/ Lucas d’Acampora Prim

      absolutely! my bad..
      thanks for warning! :)