gpt4 book ai didi

ruby-on-rails - 无法模拟 `Resolv::DNS.open`

转载 作者:行者123 更新时间:2023-12-04 10:33:48 24 4
gpt4 key购买 nike

我正在尝试使用 MiniTest/Mocks 来模拟下面的代码。但是我在运行测试时不断收到此错误。

Minitest::Assertion: unexpected invocation: #<Mock:0x7fa76b53d5d0>.size()
unsatisfied expectations:
- expected exactly once, not yet invoked: #<Mock:0x7fa76b53d5d0>.getresources("_F5DC2A7B3840CF8DD20E021B6C4E5FE0.corwin.co", Resolv::DNS::Resource::IN::CNAME)
satisfied expectations:
- expected exactly once, invoked once: Resolv::DNS.open(any_parameters)

正在测试的代码
txt = Resolv::DNS.open do |dns|
records = dns.getresources(options[:cname_origin], Resolv::DNS::Resource::IN::CNAME)
end
binding.pry
return (txt.size > 0) ? (options[:cname_destination].downcase == txt.last.name.to_s.downcase) : false

我的测试
::Resolv::DNS.expects(:open).returns(dns = mock)
dns.expects(:getresources)
.with(subject.cname_origin(true), Resolv::DNS::Resource::IN::CNAME)
.returns([Resolv::DNS::Resource::IN::CNAME.new(subject.cname_destination)])
.once

最佳答案

现在您正在测试 Resolv::DNS接收 open返回您的 mock
因为您似乎试图测试 dns模拟正在接收您需要 stub 该方法并为其提供要生成的对象的消息

试试这个:

 dns = mock 
dns.expects(:getresources)
.with(subject.cname_origin(true), Resolv::DNS::Resource::IN::CNAME)
.once
::Resolv::DNS.stub :open, [Resolv::DNS::Resource::IN::CNAME.new(subject.cname_destination)], dns do
# whatever code actually calls the "code being tested"
end
dns.verify

stub 的第二个参数是 stub 返回值和第三个参数 stub是什么将被屈服于块而不是原始屈服。

在 RSpec 中,语法更简单(也更语义化),例如:
 dns = double 
allow(::Resolv::DNS).to receive(:open).and_yield(dns)
expect(:dns).to receive(:getresources).once
.with(subject.cname_origin(true), Resolv::DNS::Resource::IN::CNAME)
.and_return([Resolv::DNS::Resource::IN::CNAME.new(subject.cname_destination)])
# whatever code actually calls the "code being tested"

关于ruby-on-rails - 无法模拟 `Resolv::DNS.open`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60284851/

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