Ruby Stubbing时间消耗操作的最佳实践

时间:2015-06-23 21:27:18

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

对测试特定情况的最佳做法感到好奇。

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

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

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

目前,我:

  1. 全局删除操作

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

  3. 代码:

    
        class BackgroundSetupWorker
          def perform
            LongOperation.the_operation
          end
        end
    
    

    并测试:

    
        LongOperation.should_receive(:the_operation)
    
    
    1. 对长时间运行的单元测试
    2. 
          before(:each) do
            LongOperation.unstub(:the_operation)
          end
      
          it "works preoperly" do
            expect(LongOperation.the_operation).to ...
          end
      
      

1 个答案:

答案 0 :(得分:2)

我认为理想的做法是将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