使用Ruby basic输出字符串测试的Rspec引发错误
我试图用Rspec编写最基本的测试,以测试标准输出上字符串的接收 我以与RSpec书中所述完全相同的方式对标准输出进行了截短,如下所示:使用Ruby basic输出字符串测试的Rspec引发错误,ruby,string,rspec,standards,output,Ruby,String,Rspec,Standards,Output,我试图用Rspec编写最基本的测试,以测试标准输出上字符串的接收 我以与RSpec书中所述完全相同的方式对标准输出进行了截短,如下所示: require './tweetag.rb' module Tweetag describe Tweet do describe "#print" do it "prints test" do output = double('output').as_null_object t = Tweetag:
require './tweetag.rb'
module Tweetag
describe Tweet do
describe "#print" do
it "prints test" do
output = double('output').as_null_object
t = Tweetag::Tweet.new(output)
t.print
output.should_receive(:puts).with('test')
end
end
end
end
module Tweetag
class Tweet
def initialize(output)
@output=output
end
def print
@output.puts('test')
end
end
end
Ruby代码如下所示:
require './tweetag.rb'
module Tweetag
describe Tweet do
describe "#print" do
it "prints test" do
output = double('output').as_null_object
t = Tweetag::Tweet.new(output)
t.print
output.should_receive(:puts).with('test')
end
end
end
end
module Tweetag
class Tweet
def initialize(output)
@output=output
end
def print
@output.puts('test')
end
end
end
正如你所看到的,没有什么真正复杂的。但是,运行规范后,我得到的答案如下:
Failures:
1) Tweetag::Tweet#print prints test
Failure/Error: output.should_receive(:puts).with('test')
(Double "output").puts("test")
expected: 1 time
received: 0 times
我尝试删除“as_null_对象”,结果是:
1) Tweetag::Tweet#print prints test
Failure/Error: t.print
Double "output" received unexpected message :puts with ("test")
谢谢您的帮助。在实际调用该方法之前,必须先使用
应该接收的方法
output = double('output').as_null_object
t = Tweetag::Tweet.new(output)
output.should_receive(:puts).with('test')
t.print
作为旁注,您的测试缺少对此处返回值的检查。您知道print方法不会引发任何异常。但是您没有检查返回值是否合适
output.should_receive(:puts).with('test').and_return('returned value')
t.print.should eql('returned value')
你的问题是什么?问题是“我应该如何让考试通过?我已经做了书上写的要通过的事情……把它写在课文中。@Zoz:这解决了你的问题吗?如果是,请将这个答案标记为已被接受。我是fait.Désole pour l'attente;)Je Découvre。