Stubbing a Kernel method?

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.

–Paul

On 10/19/07, Paul D. [email protected] wrote:

rspec-users mailing list
[email protected]
http://rubyforge.org/mailman/listinfo/rspec-users

Kernel gets mixed in to an object, so you need to stub it on the object
itself.

describe Newsreader do
it “should open the uri” do
@reader = Newsreader.new
@reader.should_receive(:open_uri).with “http://example.com/feed.xml
@reader.grab_feedhttp://example.com/feed.xml
end
end

class Newsreader
def grab_feed(uri)
response = open_uri uri
end
end

Pat

On Oct 19, 2007, at 12:18 PM, Paul D. 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

On Oct 19, 2007, at 5:18 pm, Paul D. wrote:

Kernel.should_receive(:open).with(‘filename’).and_return(‘data’)

Had this exact same issue with OpenURI myself two days ago. The
other replies are better OO but the quickest way it to use the
OpenURI.open_uri class method, which you can stub out without
interfering with Kernel. (Unless you want it to handle files as well
as URLs that is.)

BTW I have no idea what the OpenURI.open_uri method is all about, as
open-uri’s wrapper to Kernel.open does not call it. But it seems to
work…

Ashley


blog @ http://aviewfromafar.net/
linked-in @ http://www.linkedin.com/in/ashleymoran
currently @ home

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs