【问题标题】:Rspec: How to expect received message without stubbing anything or changing anything behind the scenesRspec:如何在不存根任何内容或在幕后更改任何内容的情况下预期收到的消息
【发布时间】:2018-06-19 17:22:43
【问题描述】:

我有一个 Rails 应用程序的 Rspec 测试

  describe '.move_probes_to_master_list' do
    let(:as) { create_list :a, 3, }
    let(:bs) { create_list :b, 3 }

    it 'sums the volumes' do

      active_as= [as[1], as[2]]
      b_ids = [2, 3]
      expect_any_instance_of(A)
        .to receive(:required_volume).twice.with(b_ids)
      expect_any_instance_of(A)
        .to receive(:update_move_to_master_list).twice

      expect(A.calculate_volume(active_as)).to eq(true)
    end
  end

基本上我调用A.calculate_volume 并在这个类方法中,我想确保A 类的某些成员也接收其他一些消息。我不想删除这些方法,我希望它们正常运行,但我只想验证这些方法是否被调用。

这是在循环中运行的,所以我不知道我将要处理哪些实例,但我想确保在某些成员上调用两条消息(但两次不一定是同一个成员) 的A 类总共两次。

如果我删除 expect_any_instance_of(A).to receive 期望,一切运行正常并且测试通过。

如果我保留它们,方法调用会失败并且测试会中断。

我尝试添加 and_call_original,但我觉得我是在黑暗中拍摄,因为文档并不清楚这些方法的实际操作方式。

那么,我如何验证某个类的实例是否收到了n 次消息,而无需更改有关方法调用的任何其他内容?

我错过了期望在这里收到的点吗?我不清楚为什么它首先会存根。

【问题讨论】:

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


【解决方案1】:

你可以像这样窥探这个方法:

allow(A).to receive(:calculate_volume).and_call_original

然后你可以测试calculate_volume 是否被这样调用:

expect(A).to have_received(:calculate_volume)

这样会调用原始方法,并且不会有存根,但会进行间谍活动。

【讨论】:

    【解决方案2】:

    我知道这并不能完全回答您“如何继续执行”的问题,但您应该能够将此测试分成三个不同的测试并创建一组更清晰的测试,而不必担心调用原始测试像这样:

    describe '.move_probes_to_master_list' do
      let(:as) { create_list :a, 3, }
      let(:active_as) { [as[1], as[2]] }
      let(:bs) { create_list :b, 3 }
      let(:b_ids) { [2, 3] }
      subject { A.calculate_volume(active_as) }
    
      it 'sums the volumes' do
          expect(subject).to eq(true)
      end
    
      it 'calls #required_volumen twice' do
        expect_any_instance_of(A)
          .to receive(:required_volume).twice.with(b_ids)
        subject
      end
    
      it 'calls updates_moves_to_master_list twice' do
        expect_any_instance_of(A)
          .to receive(:update_move_to_master_list).twice
        subject
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2018-01-31
      • 1970-01-01
      • 1970-01-01
      • 2017-01-07
      • 2021-03-15
      • 1970-01-01
      • 2015-07-12
      • 2013-10-23
      • 1970-01-01
      相关资源
      最近更新 更多