Search code examples
ruby-on-railsrubyhttpartywebmock

Getting Webmock to stub HTTParty requests


I am having trouble getting Webmock to work. I am using HTTParty to make GET requests. I would like to have the following request return an error:

require 'spec_helper'
require 'api_parser'
require 'httparty'

describe ApiParser do
  describe "#get_data" do
    it "returns data" do
      stub_request(:get, "congress.api.sunlightfoundation.com").to_return(:status => [401, "Forbidden"])
      puts HTTParty.get "http://congress.api.sunlightfoundation.com/bills/?history.enacted=true"
  end
end

I have added the following lines to spec_helper.rb:

require 'webmock/rspec'

WebMock.disable_net_connect!(allow_localhost: true)

But it is still calling the actual API and not being stubbed. I do not get the 401 error that I'm expecting. I'm not sure what the issue is here. Is spec_helper missing anything?

Update: I have done some testing and it looks like require api_parser is causing this issue. The stubbing works when I remove it, but it stops working when I add it. The ApiParser class is where I use HTTParty. I modified the above test to use HTTParty directly instead of using the methods in the class.


Solution

  • Found out that I was disabling Webmock in my ApiParser class (forgot to remove it while doing some debugging a few hours ago), which was overriding the config in spec_helper.