我有一个Rspec测试,它需要将Request
和HTTPI
类/模块加倍,并返回一个模拟的REST响应。我让它工作,直到这个方法发出另一个REST调用并需要返回一个新的REST响应。
API类
注意,这是一个精简版的类,但要点在那里
class API
include HTTPI
def find_device(id)
req = create_request('path')
req.body = { :customerId => MultiJson.dump(customer_id) }
return call(req)
end
def find_other_device(other_id)
req = create_request('path')
req.body = { :other_id => MultiJson.dump(other_id) }
data = call(req)
return data
end
def call(req)
response = HTTPI.send(req)
return response.body
end
end
设备文件调用REST方法
class Device
@api = API.new(:open_timeout => 30, :read_timeout => 30)
def get_device
devices = @api.find_device(@id)
log.info("First Call Made")
other_call = @api.find_other_device(@other_id)
end
end
规格文件
Rspec.describe Device do
resp = {code: 200, body: resp_body, raw_body: "TEST BODY", cookies: [cookie_list_hash]}
resp2 = {code: 200, body: resp_body_2, raw_body: "TEST BODY 2", cookies: [cookie_list_hash]}
let!(:request) {class_double('Request', new: http).as_stubbed_const} # I understand this causes the HTTPI send request to always return the same resp, but without it the test does not even get past the first call
let!(:http) {class_double('HTTPI', send: resp).as_stubbed_const}
it 'test' do
Device.get_device
end
end
我们希望做一个double,它首先返回resp var,在第二次调用:send时,它返回resp 2。
我对ruby也很陌生,所以这可能很难看。
1条答案
按热度按时间vnjpjtjt1#
我将关注您的规范,尽管您的其他类中可能需要审查一些其他内容(取决于您想要实现的内容)。如果你用另一种方式写,你可能会得到它背后的逻辑。首先,您还需要将响应定义为
let
s;你也可以看看returning different values across multiple calls。话虽如此,这可能会解决您的规范中的问题,似乎您也希望您的
api
对象是一个示例变量,而不是在您的类中定义的东西:但是,同样,这取决于你想要实现什么,如果你粘贴的代码是完整/正确与否,所以很抱歉,如果这不适用。