我对为什么不能在 Controller 规范中 stub 局部变量感到有点困惑。
这是我的 Controller :
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)
...
我的规范看起来像:
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
我仍然收到一条错误消息:
Errno::ECONNREFUSED:
Connection refused - connect(2)
我究竟做错了什么?如果我 stub
resp
变量,为什么它仍在尝试执行 HTTP 请求,在这种情况下我将如何 stub resp
变量? 最佳答案
你不能 stub 局部变量,你只能 stub 方法。在您的情况下,您可以 stub Net::HTTP.get
方法:
Net::HTTP.stub(:get).and_return(stub_resp)
关于ruby - 使用 rspec 在 Controller 中 stub API 调用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17946112/