gpt4 book ai didi

ruby - 如何在 rspec 中测试部分匹配的 puts?

转载 作者:太空宇宙 更新时间:2023-11-03 16:40:49 25 4
gpt4 key购买 nike

expect{test_method}.to output(test_str).to_stdout 有效,但仅当我在我的方法中使用 print 时。如果我使用 puts 然后测试失败,因为 puts\n 添加到末尾(我知道这是 print 之间的区别puts)。

那么有没有一种方法可以测试输出是否包含而不是等于

某个字符串?

expect(STDOUT).to receive(:puts).and include(test_str),我猜是行不通的。

最佳答案

我建议尝试正则表达式:

expect {test_method}.to output(/#{Regexp.quote(test_str)}/).to_stdout

the rspec blog 中提供了示例宣布此功能时可能会有所帮助:

expect { print "foo" }.to output("foo").to_stdout
expect { print "foo" }.to output(/fo/).to_stdout
expect { warn "bar" }.to output(/bar/).to_stderr

output matcher docs包括更多示例:

expect { print 'foo' }.to output.to_stdout
expect { print 'foo' }.to output('foo').to_stdout
expect { print 'foo' }.to output(/foo/).to_stdout

expect { do_something }.to_not output.to_stdout

expect { warn('foo') }.to output.to_stderr
expect { warn('foo') }.to output('foo').to_stderr
expect { warn('foo') }.to output(/foo/).to_stderr

expect { do_something }.to_not output.to_stderr

expect { system('echo foo') }.to output("foo\n").to_stdout_from_any_process
expect { system('echo foo', out: :err) }.to output("foo\n").to_stderr_from_any_process

Regexp.quote 的使用摘自this question's answers .基本上,如果没有它,您将无法在正则表达式的 // 中进行正确的字符串插值。

关于ruby - 如何在 rspec 中测试部分匹配的 puts?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53033939/

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