【问题标题】:Ruby Stubbing Best Practices for Time Consuming Operation用于耗时操作的 Ruby 存根最佳实践
【发布时间】:2015-09-09 21:42:46
【问题描述】:

对测试特定情况的最佳实践感到好奇。

我有一个模型,它需要一些耗时的操作来设置 - 接触外部服务、解析、内核内容等。设置的一个特定部分基本上是可选的 - 我想检查它是否已经完成运行,但结果对于几乎所有测试都无关紧要。

这个模型被用作许多其他类的输入,所以我想避免冗长的测试套件和相对不重要的步骤的霸道设置。

我想知道这是否涵盖了我的基础,或者我是否将这一切都搞错了。

目前,我是:

  1. 全局删除操作

    config.before(:each) 做 LongOperation.any_instance.stub(:the_operation) 结尾
  2. 测试它在我的后台作业中被调用

代码:

类 BackgroundSetupWorker 默认执行 LongOperation.the_operation 结尾 结尾

和测试:

LongOperation.should_receive(:the_operation)
  1. 对长时间运行的操作进行单元测试
之前(:每个)做 LongOperation.unstub(:the_operation) 结尾 它“工作前”做 期望(LongOperation.the_operation).to ... 结尾

【问题讨论】:

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


    【解决方案1】:

    我认为理想的做法是将 LongOperation 类作为参数,这样您就可以在测试中随意切换它。

    class BackgroundSetupWorker
      def initialize(op_provider = LongOperation)
        @op_provider = op_provider
      end
    
      def perform
        @op_provider.the_operation
      end
    end
    
    #in spec
    describe BackgroundSetupWorker do
      let(:op_provider){ double(the_operation: nil) }
      subject(:worker){ BackgroundSetupWorker.new(op_provider) }
    
      it 'should call op_provider' do  
        worker.perform
    
        expect(op_provider).to have_received(:the_operation)
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2012-01-16
      • 1970-01-01
      • 1970-01-01
      • 2012-09-01
      • 1970-01-01
      • 2010-11-08
      • 2019-01-14
      • 2011-02-06
      • 1970-01-01
      相关资源
      最近更新 更多