Ruby on rails Ruby stubing用于耗时操作的最佳实践

Ruby on rails Ruby stubing用于耗时操作的最佳实践,ruby-on-rails,ruby,unit-testing,rspec,Ruby On Rails,Ruby,Unit Testing,Rspec,对测试特定情况的最佳实践感到好奇 我有一个模型,它需要一些耗时的操作来建立——接触外部服务、解析、内核等。建立的一个特定部分基本上是可选的——我想检查它是否已经运行,但结果对几乎所有的测试都不重要 这个模型被用作许多其他类的输入,所以我想避免一个冗长的测试套件和一个相对不重要的步骤的傲慢设置 我想知道这是否涵盖了我的基础,或者我是否完全错了 目前,我是: 全局删除操作 config.before(:each) do LongOperation.any_instance.stub(:t

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

我有一个模型,它需要一些耗时的操作来建立——接触外部服务、解析、内核等。建立的一个特定部分基本上是可选的——我想检查它是否已经运行,但结果对几乎所有的测试都不重要

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

我想知道这是否涵盖了我的基础,或者我是否完全错了

目前,我是:

  • 全局删除操作

    config.before(:each) do LongOperation.any_instance.stub(:the_operation) end config.before(:each)do LongOperation.any_instance.stub(:_操作) 结束
  • 测试它是否在我的后台工作中被调用

  • 代码:

    类背景设置工人 def执行 长手术 结束 结束 和测试:

    LongOperation.should_receive(:the_operation) LongOperation.When_接收(:_操作)
  • 长期运行操作的单元测试
  • 在…之前做 LongOperation.unsub(:_操作) 结束 它“正常工作”吗 期望(长操作。_操作)。到。。。 结束
    我认为理想的做法是将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
    
    before(:each) do LongOperation.unstub(:the_operation) end it "works preoperly" do expect(LongOperation.the_operation).to ... end
    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