gpt4 book ai didi

ruby - 如何为特定实例 stub 实例方法?

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

我有以下案例,

class Schools::Status
def initialize(school)
@school = school
end

def active?
true
end
end

现在,我想为特定学校 stub active? 方法。

这样的一种方式

Schools::Status.new(school).stubs(:active?).returns(false)

但我的用例不同,我有学校的搜索结果,我想根据 active? 值过滤该结果,如下所示:

schools.select { |s| Schools::Status.new(school).active? }

在上面的例子中,我特别想为某些实例 stub active?

最佳答案

只需在规范中对您的类进行猴子修补。更多的 rspec 方式是使用 any_instancestub但问题是您无法访问 self stub 实例,因此您实际上没有关于 school 的信息并且您无法在该 block 中访问它。示例:

Status.any_instance.stub(:active?) { # no way to access school }

关于ruby - 如何为特定实例 stub 实例方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25378047/

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