[rspec-users] Stubbing a Kernel method?

Scott Taylor mailing_lists at railsnewbie.com
Fri Oct 19 15:17:28 EDT 2007


On Oct 19, 2007, at 12:18 PM, Paul Dlug wrote:

> Is it possible to stub a Kernel method? I'm specifically interested in
> the 'open' method to test some code using open-uri. I've tried:
>
> Kernel.should_receive(:open).with('filename').and_return('data')
>
> However, this doesn't seem to work. Any suggestions would be  
> appreciated.

Use Kernel.stub!.

Another option is to use dependency injection, and pass the mock  
kernel into your class at initialization (something like the following):


class ClassName
   def initialize(arg1, kernel=Kernel)
     @kernel = kernel
   end

   def my_func
     @kernel.open("blah")
     # do something useful here
   end
end

describe ClassName do
   before :each do
     @mock_kernel = mock(Kernel)
     @mock_kernel.stub!(:open).and_return "some text"
   end

   it "should open the file" do
     @obj = ClassName.new("hello", @mock_kernel)

     @mock_kernel.should_receive(:open).with("blah").and_return "some  
text"
     @obj.my_func
   end
end





More information about the rspec-users mailing list