【问题标题】:Rspec2: expect a few arguments among many to be calledRspec2:期望调用许多参数中的一些参数
【发布时间】:2023-03-09 05:40:01
【问题描述】:

我需要测试一段代码执行两条sql语句,我是这么说的

  ActiveRecord::Base.connection.should_receive(:execute).with("s1")
  ActiveRecord::Base.connection.should_receive(:execute).with("s2")

但是,该代码还执行了许多我不关心的其他语句,这会使测试出错。如何告诉 Rspec 确保 s1s2 在已执行语句列表中?

【问题讨论】:

  • "which trips up the test" -- 你的意思是这会让预期不起作用,还是说它会让实际代码不起作用?
  • 预期不起作用 - 在 s1s2 之前和之后执行的一些查询会触发预期错误。

标签: unit-testing activerecord rspec rspec2


【解决方案1】:

将您的 RSpec 版本更新到 2.12,您将可以访问and_call_original 方法(请参阅documentationuse cases)。使用该方法,您可以存根 ActiveRecord::Base.connectionexecute 方法并使其调用原始方法,然后添加您想要的期望:

ActiveRecord::Base.connection.stub(:execute).and_call_original
ActiveRecord::Base.connection.should_receive(:execute).with(:s1)
ActiveRecord::Base.connection.should_receive(:execute).with(:s2)

如果出于某种原因您不使用(或不想使用)最新版本的 RSpec,您可以通过以下方式实现相同的功能:

execute = ActiveRecord::Base.connection.method(:execute)
ActiveRecord::Base.connection.should_receive(:execute).with(:s1)
ActiveRecord::Base.connection.should_receive(:execute).with(:s2)
ActiveRecord::Base.connection.stub(:execute) { |*args| execute.call(*args) }

参考:

【讨论】:

  • 该死的。我确信这个答案是正确的,但我觉得奇怪的是,这么简单的事情会这么困难。
  • 更新了我的答案。我对版本号感到困惑,2.12 高于 2.8,所以您所要做的就是更新您的版本以访问 and_call_original。完成此操作后,只需添加一行:ActiveRecord::Base.connection.stub(:execute).and_call_original,它将捕获所有情况,您可以设置您的期望,而不必担心会破坏正常流程。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 2015-09-17
  • 2014-08-31
  • 2020-01-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多