gpt4 book ai didi

rspec - 如何在 rspec 中模拟实例变量

转载 作者:行者123 更新时间:2023-12-04 14:56:28 27 4
gpt4 key购买 nike

我有两个类OneClassAnotherClass :

class OneClass
def initialize(*args)
@another_member = AnotherClass.new()
end

def my_method()
if @another_member.another_method1() then
@another_member.another_method2()
end
@another_member.another_method3()
end
end

我要为 OneClass 写单元.
我该如何模拟 @another_member ?

最佳答案

您不能模拟实例变量。您只能模拟方法。一种选择是在 OneClass 中定义一个方法包装 another_member ,并模拟该方法。

class OneClass
def initialize(*args)
end

def my_method()
if another_member.another_method1() then
another_member.another_method2()
end
another_member.another_method3()
end

private

def another_member
@another_member ||= AnotherClass.new()
end

end

但是,您不必这样做,有更好的方法来编写和测试您的代码。在这种情况下,更好的模拟方法是使用名为 Dependency Injection 的模式。 .

您将依赖项传递给初始化程序。
class OneClass
def initialize(another: AnotherClass, whatever:, somethingelse:)
@another_member = another.new()
end

def my_method()
if @another_member.another_method1() then
@another_member.another_method2()
end
@another_member.another_method3()
end
end

(注意我使用了关键字参数,但您不必这样做。您也可以使用标准的 args 方法)。

然后,在测试套件中,您只需提供测试对象。
let(:test_another) {
Class.new do
def another_method1
:foo
end
def another_method2
:bar
end
def another_method3
:baz
end
end
}

it "does something" do
subject = OneClass.new(another: test_another)
# ...
end

这种方法有几个优点。特别是,您避免在测试中使用模拟,而是真正独立地测试对象。

关于rspec - 如何在 rspec 中模拟实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37248095/

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