Search code examples
rubyapirubygemsstubwebmock

What is the purpose of stubbing an HTTP request (e.g. using the WebMock gem)?


As a precursor FYI, I'm a budding developer. I'm trying to write a test for an http POST method for a Ruby gem. From what I can understand, when you stub an http response, for instance with the Ruby WebMock gem, you're basically telling it what to post and then artificially telling it what to respond with. For example, here is the code I'm trying to test:

## githubrepo.rb

module Githubrepo

include HTTParty

def self.create(attributes)

  post = HTTParty.post(
      'https://api.github.com/user/repos',

      :headers => {
        'User-Agent' => 'Githubrepo',
        'Content-Type' => 'application/json',
        'Accept' => 'application/json'
      },

      :basic_auth => {
          :username => attributes[:username],
          :password => attributes[:password]
      },

      :body => {
          'name' => attributes[:repository],
          'description' => attributes[:description]
      }.to_json
  )

Githubrepo.parse_response_from(post, attributes[:wants_ssh])

end

My RSpec test fails when I write:

Githubrepo.create(:repository => 'test', :username => 'test_user', :password => '1234')

because it makes a real HTTP request. It recommends I do the following instead:

        stub_request(:post, "https://test_user:test_password@api.github.com/user/repos").
                with(:body => "{\"name\":\"test_repo\",\"description\":null}",
                     :headers => {'Accept'=>'application/json', 'Content-Type'=>'application/json', 'User-Agent'=>'Githubrepo'}).
           to_return(:status => 200, :body => "", :headers => {})

But to me, this seems like it's pointless since it's basically telling what to send and what to respond with. I can edit the URL to say "https://bananas@git-banana.banana" and the header to say Content-type => 'Rumplestilskin' and RSpec is ok with that. How am I supposed to integrate this into testing the functionality of the create method I specified above? Or if anything, can somebody point me to a solid beginner guide or blog to help me with this question? The Ruby gem READMEs seem to assume the user knows a thing or two already about this and I don't.


Solution

  • As Steve mentions in a comment, the point of this type of test is not to test the external API but instead that your code to handle and parse the response is correct.

    As discussed in the comments to this question, check out the VCR gem for "recording" API responses to make sure your code processes them correctly: https://github.com/vcr/vcr