我试图测试方法" get_all_hotels"在我的HotelsApiService模块上:
BASE_URI = ENV['HOTELS_API_URI']
def get_all_hotels
begin
RequestService.new(BASE_URI).get("/hotels")
rescue
"Unable to get service response"
end
end
但是不能让测试通过这一点。显然问题是当我想模拟RequestService的调用时(RequestService是一个使用HTTParty来执行http请求的类)。
这是测试文件:
require "rails_helper"
describe HotelsApiService do
let(:base_uri) { "base_uri" }
let(:request_service) { double }
subject { Object.new.extend HotelsApiService }
before do
allow(ENV).to receive(:[]).with('HOTELS_API_URI') { base_uri }
end
describe "#get_all_hotels" do
let(:api_response) {
{ hotel: { id: 1, name: "Hotel name", address: "Str 34", star_rating: 3, accomodation_type: "hotel" }}
}
before do
allow(RequestService).to receive(:new).with(base_uri) { request_service }
allow(request_service).to receive(:get).with("/hotels") { api_response }
end
it 'responds with hotel' do
expect(subject.get_all_hotels).to eq(api_response.to_json)
end
end
end
像这样,测试会返回以下错误:
Failure/Error: expect(subject.get_all_hotels).to be_a_kind_of(Hotel)
#<RequestService (class)> received :new with unexpected arguments
expected: ("base_uri")
got: (nil)
Diff:
@@ -1,2 +1,2 @@
-["base_uri"]
+[nil]
Please stub a default value first if message might be received with other args as well.
如果我试图以其他方式嘲笑它:
before do
allow(RequestService).to receive_message_chain(:new, :edit).with(base_uri, "/hotels") { request_service }
end
我得到了另一个错误:
Failure/Error: expect(subject.get_all_hotels).to eq(api_response.to_json)
#<Double (anonymous)> received unexpected message :get with ("/hotels")
提前致谢
答案 0 :(得分:0)
在加载源文件时正在设置BASE_URI,这是在您模拟ENV返回预期值之前。因此它等于零,并导致您的问题。