如何在 rspec 中测试放置 [英] How to test puts in rspec
问题描述
我想做的是在命令行上运行ruby sayhello.rb
,然后从Rspec接收Hello
.
I want to do is run ruby sayhello.rb
on the command line, then receive Hello from Rspec
.
我有这个:
class Hello
def speak
puts 'Hello from RSpec'
end
end
hi = Hello.new #brings my object into existence
hi.speak
现在我想在 rspec 中编写一个测试来检查命令行输出实际上是Hello from RSpec"而不是我喜欢 Unix"
Now I want to write a test in rspec to check that the command line output is in fact "Hello from RSpec" and not "I like Unix"
不工作.我目前在 sayhello_spec.rb 文件中有这个
NOT WORKING. I currently have this in my sayhello_spec.rb file
require_relative 'sayhello.rb' #points to file so I can 'see' it
describe "sayhello.rb" do
it "should say 'Hello from Rspec' when ran" do
STDOUT.should_receive(:puts).with('Hello from RSpec')
end
end
另外,我需要实际看看我的 RSPEC 中的测试应该是什么样子.
Also, I need to actually see what the test should look like in my RSPEC please.
推荐答案
我认为最好的方法是在输出匹配器中使用 rspec build https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers/output-matcher
I think the best way is to use rspec build in output matcher https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers/output-matcher
例如,这是你的课
class MakeIt
def awesome(text)
puts "Awesome #{text}"
end
end
和你的测试
describe MakeIt do
describe '#awesome' do
it 'prints awesome things' do
expect do
MakeIt.new.awesome('tests')
end.to output('Awesome tests').to_stdout
end
it 'does not print not awesome things' do
expect do
MakeIt.new.awesome('tests')
end.to_not output('Not awesome tests').to_stdout
end
end
end
很好,干净,符合书本!
Nice, clean and by the book!
这篇关于如何在 rspec 中测试放置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!