gpt4 book ai didi

ruby - 如何避免使用 allow_any_instance_of?

转载 作者:数据小太阳 更新时间:2023-10-29 06:46:44 24 4
gpt4 key购买 nike

假设我们有以下代码:

class A
def create_server
options = {
name: NameBuilder.new.build_name
}
do_some_operations(options)
end
end

为了测试这些方法,我曾经使用allow_any_instance_of:

it 'does operations' do
allow_any_instance_of(NameBuilder).to receive(:build_name)
# test body
end

但是文档建议我们不要使用它because of several reasons .那么如何避免 allow_any_instance_of 呢?我只有一个解决方案:

class A
def create_server
options = {
name: builder.build_name
}
do_some_operations
end

private

def builder
NameBuilder.new
end
end

但是使用这种方法,代码很快就会充满几乎无用的方法(尤其是当您在所描述的类中积极使用不同对象的组合时)。

最佳答案

根据 Uzbekjon's answer 没有依赖注入(inject)(我同意)您还可以考虑取消对 NameBuilder.new 的调用,这样您就可以直接控制被测 NameBuilder 的实例:

class NameBuilder
def build_name
# builds name...
end
end

class A
def create_server
options = {
name: NameBuilder.new.build_name
}
do_some_operations(options)
end

def do_some_operations(options)
# does some operations
end
end

RSpec.describe A do
let(:a) { described_class.new }

describe '#create_server' do
let(:name_builder) { instance_double(NameBuilder) }

before do
allow(NameBuilder).to receive(:new).and_return(name_builder)
end

it 'does operations' do
# the first expectation isn't really part of what you seem
# to want to test, but it shows that this way of testing can work
expect(name_builder).to receive(:build_name)
expect(a).to receive(:do_some_operations)
a.create_server
end
end
end

关于ruby - 如何避免使用 allow_any_instance_of?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36641976/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com