gpt4 book ai didi

Ruby rspec 模拟一个类

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

我有一个包含两个类的文件。

class LogStash::Filters::MyFilter< LogStash::Filters::Base

class LogStash::JavaMysqlConnection

JavaMysqlConnection 有方法 initializeselect。它由 MyFilter 类使用,您可能已经猜到了,用于查询数据库。

如何模拟 initializeselect 方法分别返回 nil 和数组?

我尝试使用:

before(:each) do
dbl = double("LogStash::JavaMysqlConnection", :initialize => nil)
end

但这没有用,因为我仍然看到通信链接失败。

我有 rspec 版本 2.14.8

提前致谢。附言。我是 Ruby 新手

最佳答案

差(工作):Read more as to why exactly it is a bad practice

allow_any_instance_of(LogStash::JavaMysqlConnection)
.to receive(:select)
.and_return([])

好:

let(:logstash_conn) { instance_double(LogStash::JavaMysqlConnection) }

allow(LogStash::JavaMysqlConnection)
.to receive(:new)
.and_return(logstash_conn)

allow(logstash_conn)
.to receive(:select)
.and_return([])

Docs

RSpec

关于Ruby rspec 模拟一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41982953/

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