RSpec实例双重期望值和默认参数值

时间:2015-08-05 20:02:12

标签: ruby unit-testing rspec

我正在尝试为一个类创建单元测试,该类依赖于我创建的对象WebClient,该对象会生成经过身份验证的Web请求。我创建了一个instance_double WebClient我已经传入对象并正在模拟其中一个公共方法make_json_request,其中包含几组{{1}期望所以它可以返回我可以在单元测试中使用的一些哈希值。

在我测试的第一种方法中,调用方法如下:

with

我正在设置我的@web_client.make_json_request '/api/v1/endpoint', query: { territory: territory_id, status: 'active' }

instance_double

当我尝试在rspec中运行测试时,出现以下错误:

web_client = instance_double('WebClient')

expect(web_client).to receive(:make_json_request)
   .with('/api/v1/endpoint', query: { territory: territory_id, status: 'active' })
   .and_return nil

由于某种原因(下面的方法签名),它似乎正在接收带有方法签名中定义的默认值的消息:

Failure/Error: state = client.current_state
 #<InstanceDouble(WebClient) (anonymous)> received :make_json_request with unexpected arguments
   expected: ("/api/v1/endpoint", {:query=>{:territory=>1, :status=>"active"}})
        got: ("/api/v1/endpoint", {:query=>{}})
 Diff:
 @@ -1,2 +1,2 @@
 -["/api/v1/endpoint", {:query=>{:territory=>1, :status=>"active"}}]
 +["/api/v1/endpoint", {:query=>{}}]

我知道一个事实是它在实际传递带有适当值的命名参数的线路上没有达到预期,而且我不知道如何解决这个问题。在我使用双精度的其他情况下,我没有遇到过这个问题 - 只有在这种情况下才会出现这个问题,命名参数的默认值为。我做错了什么?

编辑:我被要求提供正在测试的方法的完整代码:

def make_json_request(path, method: :get, body: {}, query: {})

编辑2 :完整规范:

def load_entities(territory_id)
    path = '/api/v1/endpoint'
    @web_client.make_json_request path, query: { territory: territory_id, status: 'active' }
    .select { |d| d['status'] == 'active' }
end

1 个答案:

答案 0 :(得分:1)

案件结案!罪魁祸首:语法错误。

改变这个:

@web_client.make_json_request path, query: { territory: territory_id, status: 'active' }
.select { |d| d['status'] == 'active' }

进入这个:

@web_client.make_json_request(path, query: { territory: territory_id, status: 'active' }).select { |d| d['status'] == 'active' }

因为您在#select对象上执行query,而不是在make_json_request的结果中进行操作。它不会从query中选择任何内容,如规范所示。