ruby-on-rails - RSpec:receive_message_chain的匹配参数

标签 ruby-on-rails rspec

我正在尝试 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方法以外的任何内容时,似乎都不能将withreceive_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/

相关文章:

ruby-on-rails - 依赖销毁不起作用,has_many :model, :dependent => :destroy

ruby-on-rails - 在 Rails 3 中使用 Scrapi .. 出现段错误/中止陷阱

ruby-on-rails - Sidekiq::测试.假的!不伪造 Sidekiq::Queue

ruby-on-rails - 包含可选参数的方法的 RSpec 参数匹配器

ruby-on-rails - Heroku Rails Websolr,太阳黑子在生产中不是免费的吗?

ruby-on-rails - 根据模型验证自定义设计闪存消息

ruby-on-rails - Rails 用户个人资料页面只能由正确的用户访问

ruby-on-rails - rake 规范给我错误

ruby - 运行 RSpec 时找不到库类

ruby - 我如何在 block 之前的 "expect"更改 rspec 中的某些内容?