rubytestingrequeststubbingfaraday

Ruby stubbing with faraday, can't get it to work


Sorry for the title, I'm too frustrated to come up with anything better right now.

I have a class, Judge, which has a method #stats. This stats method is supposed to send a GET request to an api and get some data as response. I'm trying to test this and stub the stats method so that I don't perform an actual request. This is what my test looks like:

describe Judge do
  describe '.stats' do

    context 'when success' do
      subject { Judge.stats }

      it 'returns stats' do
        allow(Faraday).to receive(:get).and_return('some data')

        expect(subject.status).to eq 200
        expect(subject).to be_success
      end
    end
  end
end

This is the class I'm testing:

class Judge

  def self.stats
    Faraday.get "some-domain-dot-com/stats"
  end

end

This currently gives me the error: Faraday does not implement: get So How do you stub this with faraday? I have seen methods like:

    stubs = Faraday::Adapter::Test::Stubs.new do |stub|
      stub.get('http://stats-api.com') { [200, {}, 'Lorem ipsum'] }
    end

But I can't seem to apply it the right way. What am I missing here?


Solution

  • Note that Faraday.new returns an instance of Faraday::Connection, not Faraday. So you can try using

    allow_any_instance_of(Faraday::Connection).to receive(:get).and_return("some data")
    

    Note that I don't know if returning "some data" as shown in your question is correct, because Faraday::Connection.get should return a response object, which would include the body and status code instead of a string. You might try something like this:

    allow_any_instance_of(Faraday::Connection).to receive(:get).and_return(
       double("response", status: 200, body: "some data")
    )
    

    Here's a rails console that shows the class you get back from Faraday.new

    $ rails c
    Loading development environment (Rails 4.1.5)
    2.1.2 :001 > fara = Faraday.new
     => #<Faraday::Connection:0x0000010abcdd28 @parallel_manager=nil, @headers={"User-Agent"=>"Faraday v0.9.1"}, @params={}, @options=#<Faraday::RequestOptions (empty)>, @ssl=#<Faraday::SSLOptions (empty)>, @default_parallel_manager=nil, @builder=#<Faraday::RackBuilder:0x0000010abcd990 @handlers=[Faraday::Request::UrlEncoded, Faraday::Adapter::NetHttp]>, @url_prefix=#<URI::HTTP:0x0000010abcd378 URL:http:/>, @proxy=nil>
    2.1.2 :002 > fara.class
     => Faraday::Connection