2

to an API call during the test,I want to stub the OpenURI-open-method to return a file which content I packed up in a constant. However, in the same parsing method, all other calls to OpenURI open should be handled normally

@obj.should_receive(:open).with do |arg|
  if arg == mypath # mypath is a string constant like "http://stackoverflow.com/questions"
    obj=double("object_returned_by_openuri_open") # create a double
    obj.stub(:read).and_return(TESTFILE) # with a stub
    obj #return the double
  else
    open(arg) # call original Open URI method in all other cases
  end
end

However, when calling the parsing method, this does not work and it returns "NoMethodError: undefined method read for nil:NilClass" in the line f = open(mypath).read of my parsing method.

Does anybody know how can achieve this sort of "partial method stubbing" (stubbing a method for one specific argument, call original for others). The other files are Images, so I don't want to store them as constants in my source code. In an extension to make the tests network-independent, I could also return an local image file in the else-case.

I would be glad about any suggestions and hints :)

Yo Ludke
  • 2,149
  • 2
  • 23
  • 38

2 Answers2

1

very similar to this question

This should work

original_method = @obj.method(:open)
@obj.should_receive(:open).with do |arg|
  if arg == mypath # mypath is a string constant like "https://stackoverflow.com/questions"
   obj=double("object_returned_by_openuri_open") # create a double
   obj.stub(:read).and_return(TESTFILE) # with a stub
   obj #return the double
 else
   original_method.call(arg) # call original Open URI method in all other cases
 end
end
Community
  • 1
  • 1
kp2222
  • 94
  • 4
  • Thanks for pointing my to the other question - I think my mistake was that due to the subtle ".with" before "do |arg|", it didn't return any return values. Now it works for me (I use `@s.should_receive(:open).at_least(:once) do |arg|`) – Yo Ludke Nov 28 '12 at 08:24
0

Have you considered using the fakeweb gem? I believe it patches Net::HTTP, which OpenURI's open method wraps.

FakeWeb.register_uri(:get, "http://stackoverflow.com/questions", :body => File.open(TESTFILE, "r"))
Abe Voelker
  • 30,124
  • 14
  • 81
  • 98
  • Thanks for this hint, I guess this good be a good way to go in the long run as the test suite progresses (sorry, have too few points to vote up) – Yo Ludke Nov 28 '12 at 08:27