0

I am trying to mock an API get request (get_organization) to show a page with the organization's info. I am using an ApiClient service.

It works in practice, but when I try to stub the api request I get:

Failure/Error: if org_api_request[:id].present? && org_api_request[:id] == @org_id
       #<InstanceDouble(ApiClient) (anonymous)> received unexpected message :[] with (:id)

I tried to add different versions of expect(ApiClient).to receive([]).with(first_org[:id]) (with and without the .with statement) but all I get in response is ApiClient does not implement: []

The stub request:

stub_api_client(message: :get_organization, success: true, response: default_single_provider_org)

Organization Controller

def show
  @org_id = params[:org_id]

  org_api_request = api_service.get_organization(@org_id)

  if org_api_request[:id].present? && org_api_request[:id] == @org_id
    @org = org_api_request
  else
    flash[:alert] = "We were unable to connect to API"
    redirect_to root_path
  end
end

What I tried

I tried this solution

stub = stub_api_client(message: :get_organization, success: true, response: default_get_provider_org_response)
allow(stub).to receive(:[]).with(:id)

(with and without the .with(:id))

But I get this error:

the ApiClient class does not implement the instance method: []
everyday_potato
  • 113
  • 1
  • 1
  • 14
  • What is `default_get_provider_org_response`? – spickermann Aug 03 '21 at 16:56
  • What is `stub_api_client`? You're only showing us half of the puzzle. – Tom Lord Aug 03 '21 at 17:23
  • In theory I think your approach looks good, **except** it appears your `stub_api_client` method is actually returning the **`ApiClient` class**, and not the `api_request` object -- which means your second stub is actually acting on the "wrong" object. – Tom Lord Aug 03 '21 at 17:27

0 Answers0