【问题标题】:Rspec expect to recieve message with attributes and ignore othersRspec期望接收带有属性的消息并忽略其他消息
【发布时间】:2018-01-02 08:12:52
【问题描述】:

我一直在尝试编写规范。

我需要测试一下:

expect(Foo).to receive(:bar).with(some_args)

除非Foo 只收到一次bar,否则一切都会正常进行。但它肯定会收到bar 多次,因此更高的字符串会失败并显示

#<Foo (class)> received :bar with unexpected arguments

关于那些电话。

我如何测试Foo 接收bar 并使用我需要的确切参数并忽略其他情况?

【问题讨论】:

    标签: ruby-on-rails rspec test-double


    【解决方案1】:

    使用allow(Foo).to receive(:bar).and_call_original怎么样?

    例如,这些测试将成功通过:

    class Foo
      def boo(b)
        b
      end
    end
    
    describe Foo do
      let(:a) { Foo.new }
    
      before do
        allow(a).to receive(:boo).and_call_original
      end
    
      it do
        expect(a).to receive(:boo).with(2)
    
        expect(a.boo(1)).to eq 1
        expect(a.boo(2)).to eq 2
        expect(a.boo(3)).to eq 3
      end
    end
    

    如果您将expect(a).to receive(:boo).with(4) 添加到块中,则测试将失败。看起来就是您要找的东西,对吧?

    【讨论】:

    • 就是这样。我以为我试过了,但没有成功。但是我现在又试了一次,一切都完成了,thanx! (我自己尝试时一定忘记保存更改,因为我已经将这一行注释掉了:))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-11
    • 2021-12-11
    • 2014-11-12
    • 1970-01-01
    • 2018-01-04
    相关资源
    最近更新 更多