Search code examples
rubyrspecwebmock

Using RSpec/webmock to stub requests for various status codes


I need to stub requests to an external API with webmock/webmock but I need to test for a handful of responses (200, 404, 503, etc.). What's the best way to do this cleanly? My first hacky thought was that you can set something unique in the headers, like a unique User-Agent string, to key in on but it leads me to write terrible code like this:

# spec/spec_helper.rb
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'the_geek'
require 'webmock/rspec'
WebMock.disable_net_connect!(allow_localhost: true)
RSpec.configure do |config|
  config.before(:each) do
    stub_request(:get, /www.boardgamegeek.com/).
      with(headers: {'Accept'=>'*/*', 'User-Agent'=>'SOME 200 STRING'}).
      to_return(status: 200, body: "stubbed response", headers: {})

    stub_request(:get, /www.boardgamegeek.com/).
      with(headers: {'Accept'=>'*/*', 'User-Agent'=>'SOME 404 STRING'}).
      to_return(status: 404, body: "Not Found", headers: {})

    stub_request(:get, /www.boardgamegeek.com/).
      with(headers: {'Accept'=>'*/*', 'User-Agent'=>'SOME 503 STRING'}).
      to_return(status: 503, body: "Not Found", headers: {})
  end
end

I've looked at VCR, but from what I understand it can be hard to simulate and capture errors with it. Is there another clean and succinct way to stub out requests for multiple response codes? Thanks!


Solution

  • Whatever library you're using to make HTTP requests has a way of returning the response status. I would use RSpec stubs to stub the library to return the status (and whatever else about the response) you need in each example. In addition to requiring less code than the webmock approach, this would have the advantage that everything you'd need to read to understand each example would be right there in the example rather than off in spec_helper.rb.

    If that's not clear, feel free to add the code that makes the request to your question and I could give an example of how to stub it here.

    I wouldn't worry about webmock at all in specs that need to return error statuses; it would still be preventing you from making HTTP requests, but you wouldn't be, since you'd be stubbing them out.