我正在 rspec 上编写一个测试,需要为位置模型允许以下行:
Location.where(id: params[:id]).first
但这是不正确的(两个参数而不是一个错误):
allow(Location).to receive(:where, :first).with(id: my_id)
这也是:
allow(Location).to receive(:where).with(id: my_id).first
哪种方法是正确的?
你可以这样做:
allow(Location).to receive(:where).with(id: my_id).and_return double(first: <your Location mock here>)
where
返回关系(可枚举类型或集合)。因此,如果你想模拟你的位置,你需要返回某种集合:
allow(Location).to receive(:where).with(id: my_id).and_return([double('result')])
也就是说,您始终可以替换 where(...) 的模式。首先是 find_by(...):
Location.find_by(id: params[:id])
allow(Location).to receive(:find_by).with(id: my_id).and_return(double('result'))
这样,您就不需要返回集合,以便可以先调用它。您立即得到第一个结果。
如果您确实无法修改代码,也无法修改结果 - 您基本上只想允许特定的合约 - 那么您可以使用message_chains,如使用旧代码部分所述:
allow(Location).to receive_message_chain(:where, :first)