代码之家  ›  专栏  ›  技术社区  ›  Wayne Conrad

RSpec:指定每次对具有不同参数的方法的多个调用

  •  34
  • Wayne Conrad  · 技术社区  · 16 年前

    在rspec(1.2.9)中,指定一个对象每次将接收到对一个具有不同参数的方法的多个调用的正确方法是什么?

    我问是因为这个令人困惑的结果:

    describe Object do
    
      it "passes, as expected" do
        foo = mock('foo')
        foo.should_receive(:bar).once.ordered.with(1)
        foo.should_receive(:bar).once.ordered.with(2)
        foo.bar(1)
        foo.bar(2)
      end
    
      it "fails, as expected" do
        foo = mock('foo')
        foo.should_receive(:bar).once.ordered.with(1) # => Mock "foo" expected :bar with (1) once, but received it twice
        foo.should_receive(:bar).once.ordered.with(2)
        foo.bar(1)
        foo.bar(1)
        foo.bar(2)
      end
    
      it "fails, as expected" do
        foo = mock('foo')
        foo.should_receive(:bar).once.ordered.with(1)
        foo.should_receive(:bar).once.ordered.with(2)
        foo.bar(2) # => Mock "foo" received :bar out of order
        foo.bar(1)
      end
    
      it "fails, as expected, but with an unexpected message" do
        foo = mock('foo')
        foo.should_receive(:bar).once.ordered.with(1)
        foo.should_receive(:bar).once.ordered.with(2)
        foo.bar(1)
        foo.bar(999) # => Mock "foo" received :bar with unexpected arguments
                     # =>   expected: (1)
                     # =>         got (999)
      end
    
    end
    

    我希望最后一条失败消息是“预期:(2)”,而不是“预期(1)”。我是否错误地使用了rspec?

    1 回复  |  直到 16 年前
        1
  •  41
  •   Community Mohan Dere    9 年前

    与此类似 question . 建议的解决方案是调用 as_null_object

    describe Object do
      it "fails, as expected, (using null object)" do
        foo = mock('foo').as_null_object
        foo.should_receive(:bar).once.ordered.with(1)
        foo.should_receive(:bar).once.ordered.with(2)
        foo.bar(1)
        foo.bar(999) # => Mock "foo" expected :bar with (2) once, but received it 0 times
      end
    end
    

    输出与您的第二个案例不同(即“预期2但得到999”),但它确实表明未达到预期。

    推荐文章