我正在尝试 stub :
Thing.where(uuid: options['uuid']).first
通过:
allow(Thing).to receive_message_chain(:where, :first)
.with(uuid: thing_double.uuid)
.and_return(nil)
但这正在返回:
#<Double (anonymous)> received :first with unexpected arguments
expected: ({:uuid=>123})
got: (no args)
我应该使用其他方法来验证消息链的参数吗?
最佳答案
当参数涉及除 final方法以外的任何内容时,似乎都不能将with
与receive_message_chain
结合使用。因此消息:
#<Double (anonymous)> received :first with unexpected arguments
这很有道理-RSpec如何知道链中的哪个方法应该接收参数?
要验证参数的期望值,请不要对链进行 stub 处理,而只需对
where
进行 stub 处理即可allow(Thing).to receive(:where).with(uuid: 1).and_return([])
expect(Thing.where(uuid: 1).first).to eq nil
或忽略参数:
allow(Thing).to receive_message_chain(:where, :first).and_return(nil)
expect(Thing.where(uuid: 1).first).to eq nil
不建议IMO使用
receive_message_chain
。从文档中:you should consider any use of receive_message_chain a code smell
关于ruby-on-rails - RSpec:receive_message_chain的匹配参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38334499/