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