Home > Mobile >  Stub Httparty call: Wrong number of arguments (given 2, expected 1)
Stub Httparty call: Wrong number of arguments (given 2, expected 1)

Time:09-19

I created a simple ruby file (not Rails) and I am trying to test (using Rspec) a method where I am calling an API. In the test I am trying to mock the call via WebMock but it keeps giving me this error:

Requests::FilesManager#display fetches the files from the API
     Failure/Error: Requests::FilesManager.new.display
     
     ArgumentError:
       wrong number of arguments (given 2, expected 1)

The files are:

#run.rb
module Requests
  require "httparty"
  require 'json'

  class FilesManager
      include HTTParty

      def initialize

      end

      def display
        response = HTTParty.get('https://api.publicapis.org/entries', format: :json)
        parsed_response = JSON.parse(response.body)
        puts "The secret message was: #{parsed_response["message"]}"
      end
  end
end

and the spec file:

require 'spec_helper'
require_relative '../run'

RSpec.describe Requests::FilesManager do
  describe "#display" do
    it 'fetches the files from the API' do
      stub_request(:get, "https://api.publicapis.org/entries").
        to_return(status: 200, body: "", headers: {})

      Requests::FilesManager.new.display
    end
  end
end

EDIT: So the error seems to come from the line:

JSON.parse(response.body)

If I comment it out it disappears. The problem then is that the output of the call is not a json (even with the format: :json when calling the HTTParty). I tried other solutions but nothing seems to work in making the response json. It is just a string.

CodePudding user response:

Change

response = HTTParty.get('https://api.publicapis.org/entries', format: :json)

to

response = HTTParty.get('https://api.publicapis.org/entries').

I think you don't need the format: :json more so when you explicitly format the response to JSON anyway.

CodePudding user response:

You need to return a json object in the body parameter of the stubbed response:

E.g: For an empty response:

  stub_request(:get, "https://api.publicapis.org/entries").
    to_return(status: 200, body: "".to_json, headers: {})

OR For a valid response: (Note: You may have to require json to convert a hash to json)

require 'json'
...

  stub_request(:get, "https://api.publicapis.org/entries").
    to_return(status: 200, body:  { entries: { '0': { message: "Hello World" } } }.to_json, headers: {})

CodePudding user response:

Solved!

  1. It seems there was an error because the json gem version that HTTParty uses is too old.

  2. Moved on to RestClient gem for the RESTful API calls. It had another conflict in the mime gem versioning.

  3. Finally moved to Faraday and that solved my problems:

JSON.parse(response.body, :quirks_mode => true)
  • Related