Search code examples
rubyexceptionrspecopen-uri

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


Solution

  • 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))