【问题标题】:rspec at_least once using with condition not working as I would expectrspec at_least 一次使用条件不符合我的预期
【发布时间】:2014-02-05 16:53:49
【问题描述】:

如果该方法在其他时间使用不同的参数调用,是否有一种方法可以测试该方法是否至少使用参数匹配器调用一次。这是一个例子:

class A
  def test(a)
    puts "AAA"
  end
end

it "should work" do
  a = A.new
  expect(a).to receive(:test).with(1).at_least(:once)
  a.test 2
  a.test 1
  a.test 3
end

我只是担心使用某个参数至少调用了一次测试,但是当第一次使用不匹配的参数调用该测试时,我得到了预期失败。

更新 我想要做的一个更好的例子是比这更复杂一点......我想对参数进行自定义匹配......更像是

it "should work" do
  a = A.new
  expect(a).to receive(:test).at_least(:once).with(an_instance_of(Fixnum)) do |i|
    expect(i).to be > 2
  end
  a.test 2
  a.test 1
  a.test 3
end

当我过去使用 mocha 时,您可以将一个块传递给 with 方法来评估参数。如果块返回 false,则参数期望失败。似乎 rspec 只允许您使用返回块检查参数(当您使用 and_call_original 时会被忽略)。

【问题讨论】:

    标签: rspec


    【解决方案1】:

    我认为您需要使用as_null_object 基本上忽略带有其他参数的调用。

    换行:

    a = A.new
    

    收件人:

    a = A.new.as_null_object
    

    【讨论】:

    • 这确实有效,但它会导致对象变成一个完整的模拟对象。这意味着我不能再在其上使用 and_call_original。此外,文档说它只适用于启用应该语法的情况。
    • 还有一件事,如果我想对传入的参数使用更复杂的期望,这不起作用...请参阅我对原始帖子的更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    • 2014-10-04
    • 2023-03-13
    相关资源
    最近更新 更多