代码之家  ›  专栏  ›  技术社区  ›  crispy

Rspec:如何测试递归?

  •  8
  • crispy  · 技术社区  · 16 年前

    我想测试一个方法是否用一个特定的参数递归调用。

    我的方法:

    class Recursable
      def rec(arg)
        rec(7) unless arg == 7
      end
    end
    
    describe Recursable do
      it "should recurse" do
        r = Recursable.new('test')
        r.should_receive(:rec).with(0).ordered
        r.should_receive(:rec).with(7).ordered
        r.rec(0)
      end
    end
    

    意外地,RSpec失败:

    expected :rec with (7) once, but received it 0 times
    

    2 回复  |  直到 16 年前
        1
  •  10
  •   Nick Lewis    16 年前

    r.should_receive(:rec) 正在替换 r#rec 用存根,当然不会打电话给你 r.rec(7) .

    更好的方法是简单地测试初始方法调用的结果是否正确。严格来说,方法是否递归、迭代或给朋友打电话并不重要,只要它最终给出了正确的答案。

        2
  •  2
  •   tothemario    13 年前

    通常,如果您需要测试递归,这是一种代码味道;您可能应该将方法划分为不同的职责或其他内容。

    但有时您只需要对递归添加一些基本检查。 你可以用Rspec来做 and_call_original :

    it "should recurse" do
      r = Recursable.new('test')
      r.should_receive(:rec).with(0).ordered.and_call_original
      r.should_receive(:rec).with(7).ordered.and_call_original
      r.rec(0)
    end
    

    正常情况下 should_receive 你称之为原创 存根方法(包含测试检查)也将调用原始方法实现,该实现将按预期执行递归。

    推荐文章