使用rspec在控制器中调用API调用

Nee*_*ran 2 ruby rspec stubbing

我只是有点困惑为什么我不能在我的控制器规范中存根局部变量.

这是我的控制器:

Class UsersController < ApplicationController
    ...
    def get_company
        resp = Net::HTTP.get("http://get_company_from_user_id.com/#{params[:id]}.json")
        @resp = JSON.parse(resp.body)
        ...
Run Code Online (Sandbox Code Playgroud)

我的规格如下:

class ResponseHelper
    def initialize(body)
        @body = body
    end
end

describe "Get company" do
it "returns successful response" do
        stub_resp_body = '{"company": "example"}' 
        stub_resp = ResponseHelper.new(stub_resp_body)
    controller.stub!(:resp).and_return(stub_resp)
    get :get_company, {:id => @test_user.id}
    expect(response.status).to eq(200)
    end
end
Run Code Online (Sandbox Code Playgroud)

我仍然得到一个错误说:

 Errno::ECONNREFUSED:
 Connection refused - connect(2)
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?如果我正在对resp变量进行存根,为什么它仍在尝试执行HTTP请求resp?在这种情况下如何存根变量?

tor*_*o2k 6

你只是不能存根本地变量,你只能存根方法.在您的情况下,您可以存根Net::HTTP.get方法:

Net::HTTP.stub(:get).and_return(stub_resp)
Run Code Online (Sandbox Code Playgroud)