我刚开始在Ruby中使用RSpec进行单元测试,我在执行一个非常基本的单元测试时遇到了困难。我习惯于使用Python和JavaScript进行单元测试,而且通常不会遇到这个问题。
我只是尝试使用puts语句来测试STDOUT。这是我的规格。
my_spec.rb
require 'my_file'
describe C do
before(:all) do
@c = C.new
end
describe C do
subject(:C) { described_class.new }
it 'should print Hello World' do
expect {@c.main}.to output("Hello world").to_stdout
end
end
end这是my_file.rb
class C
def main
puts "Hello World"
end
end这里没有主要代码,只是对输出的简单测试,但是当我运行规范时,我收到了一个NoMethodError错误:
Failures:
1) C C should print Hello World
Failure/Error: expect {@c.main}.to output("Hello world").to_stdout
NoMethodError:
undefined method `main' for #<C:0x007fe54488a550>
# ./spec/my_spec.rb:12:in `block (4 levels) in <top (required)>'
# ./spec/my_spec.rb:12:in `block (3 levels) in <top (required)>'它说我有一个未定义的方法main,当我在my_file.rb中定义它时,我知道这个错误通常是因为我在定义方法之前调用它。不过,不确定我在这里做错了什么,因为我认为这个方法已经定义好了。任何帮助都是非常感谢的!
发布于 2016-05-18 19:09:46
我想出两个可能的原因:
1)在运行时加载的my_file可能不是您认为的那个。我建议在其中放置一些东西,比如puts或raise,看看是否真的在运行该文件。
您可能希望使用require_relative而不是require,因为这将使您更好地控制加载哪个文件。
2)你有两个describe。我建议去掉里面的那个。
此外,规范文件中的1行有两个错误;以下是更正的版本:
expect {@c.main}.to output("Hello World\n").to_stdout“World”没有大写,在"Hello World“结尾没有”n“。
https://stackoverflow.com/questions/37307893
复制相似问题