Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raising OpenURI::HTTPError caused wrong number of arguments error

I am testing how a method handles a 302 HTTPError exception. I tried to stub the one method call to raise one programmatically, however it keep complaining that wrong number of arguments error (0 for 2)

the code tested this particular line:

document = Nokogiri.HTML open(source_url)

and in the spec I stubbed it like this:

subject.stub(:open).and_raise(OpenURI::HTTPError)
subject.should_receive(:ended=).with(true)
subject.update_from_remote

I don't think it is related to Nokogiri.HTML() or Open-uri.open(), so why is this happening?

Also, how would I try to make this HTTPError as a 302 redirect error? Thanks

like image 222
lulalala Avatar asked Nov 28 '11 07:11

lulalala


2 Answers

I found out that OpenURI::HTTPError's constructor requires two parameters. Rspec by default will call the error class's new method with no parameter, which cause this error. So I need to manually create an error object by passing the required parameters.

exception_io = mock('io')
exception_io.stub_chain(:status,:[]).with(0).and_return('302')          
subject.stub(:open).with(anything).and_raise(OpenURI::HTTPError.new('',exception_io))
like image 150
lulalala Avatar answered Oct 13 '22 20:10

lulalala


This is a very late reply, but for others who may find this helpful: if you use the FakeWeb gem in conjunction with Nokogiri, you can do this kind of testing without having to get so involved with the internals of the code. You can register a URI with FakeWeb in your test, and tell it what to return. For example:

FakeWeb.register_uri(:get, 'http://www.google.com', :status => ['404', 'Not Found'])

The URI argument you provide needs to match the URI your method is calling. FakeWeb will then intercept the call, and return the status you provide.

like image 36
Mike T Avatar answered Oct 13 '22 20:10

Mike T