I'm updating an application that was working with a very old version of RSpec (2.9.0). It works fine with 3.8, but I get a deprecation error about the following code:

            response = Net::HTTPOK.new(1.0, "200", "OK")
            response.stub(:content_type => 'text/json', :body => contents_raw)

Now, this code is a mock callout to an external API, and it is deep inside my code's libraries. The application I'm testing is a Sinatra app, so I'm using "get" from Rack::Test::Methods to test my app, but then deep inside the app itself is this response.stub

Apparently I should be using "double()" and "allow(object).to receive(...)", but all the examples I've seen are for using double directly in your test's "it" block, which this code is nowhere near. If I actually try to use double I just get a no method error.

WebMocks seems like a very large hammer to just replace this single call.

Maybe the right thing to do is to make a superclass of Net::HTTPOK and pass the response data in wit that superclass's new?

2 Answers

0
rlpowell On

Huh. OK, so the wrapper class method turned out to be far easier than I expected. In my spec file I added:

class HttpWrapper < Net::HTTPOK
    def initialize(data, *args)
        @data = data
        super(*args)
    end

    def content_type
        'text/json'
    end

    def body
        @data
    end
end

(Bizarre detail: if I replace every instance of "data" above with "body", it explodes horribly.)

And at the block of code in question I now have:

            response = HttpWrapper.new(contents_raw, 1.0, "200", "OK")

And that seems to have done the trick just fine.

If this is a terrible idea for some reason, hopefully someone will let me know. :)

0
Community On

the best way to mock http, use gem which called iswebmock