Ruby脚本的Rspec测试问题,该脚本接受用户对哈希元素的输入



我有一个ruby脚本,它在运行时从用户那里获取书籍的价格。我是为Ruby脚本编写RSpec测试的新手。我使用的是Ruby 1.9.3-p327和rspec 2.11.0。您可以Github此链接克隆我的项目。

我的Rspec测试旨在测试新实例化的对象是否属于特定的类。

如果我在ruby脚本中注释第32行,我的测试就会成功通过。

不知怎么的,当我取消注释那一行时,我得到了下面的错误,这与用户输入有关。我甚至没有将其作为规范文件的一部分进行测试,但我仍然遇到了这个错误。我不知道我为什么以及如何解决这个问题。

The Last Samurai: /home/mohnish/xxx/yyy/sample_pocs/book/book.rb:11:in `gets': Is a directory - spec (Errno::EISDIR)
    from /home/mohnish/xxx/yyy/sample_pocs/book/book.rb:11:in `gets'
    from /home/mohnish/xxx/yyy/sample_pocs/book/book.rb:11:in `block in get_prices'
from /home/mohnish/xxx/yyy/sample_pocs/book/book.rb:9:in `each'
    from /home/mohnish/xxx/yyy/sample_pocs/book/book.rb:9:in `inject'
    from /home/mohnish/xxx/yyy/sample_pocs/book/book.rb:9:in `get_prices'
from /home/mohnish/xxx/yyy/sample_pocs/book/book.rb:49:in `<top (required)>'
    from /home/mohnish/xxx/yyy/sample_pocs/book/spec/spec_helper.rb:1:in `require_relative'
    from /home/mohnish/xxx/yyy/sample_pocs/book/spec/spec_helper.rb:1:in `<top (required)>'
from /home/mohnish/.rvm/rubies/ruby-1.9.3-p327/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /home/mohnish/.rvm/rubies/ruby-1.9.3-p327/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /home/mohnish/xxx/yyy/sample_pocs/book/spec/book_spec.rb:1:in `<top (required)>'
from /home/mohnish/.rvm/gems/ruby-1.9.3-p327@book_set/gems/rspec-core-2.11.1/lib/rspec/core/configuration.rb:780:in `load'
    from /home/mohnish/.rvm/gems/ruby-1.9.3-p327@book_set/gems/rspec-core-2.11.1/lib/rspec/core/configuration.rb:780:in `block in load_spec_files'
    from /home/mohnish/.rvm/gems/ruby-1.9.3-p327@book_set/gems/rspec-core-2.11.1/lib/rspec/core/configuration.rb:780:in `map'
from /home/mohnish/.rvm/gems/ruby-1.9.3-p327@book_set/gems/rspec-core-2.11.1/lib/rspec/core/configuration.rb:780:in `load_spec_files'
    from /home/mohnish/.rvm/gems/ruby-1.9.3-p327@book_set/gems/rspec-core-2.11.1/lib/rspec/core/command_line.rb:22:in `run'
    from /home/mohnish/.rvm/gems/ruby-1.9.3-p327@book_set/gems/rspec-core-2.11.1/lib/rspec/core/runner.rb:69:in `run'
from /home/mohnish/.rvm/gems/ruby-1.9.3-p327@book_set/gems/rspec-core-2.11.1/lib/rspec/core/runner.rb:8:in `block in autorun'

我还想测试这个例子的用户输入。如果你能告诉我,我怎么也能做到这一点,那就太好了。我发现了一些可以开始测试用户输入的地方,比如eg 1和eg 2,但我主要研究如何测试属于哈希的许多元素的用户输入

谢谢。

使用

STDIN.gets.chomp

看看这个答案。

测试这一点的最佳方法是用一个返回固定响应的对象和方法来模拟IO#gets。RSpec模拟看起来像:

STDIN.should_receive(:gets).and_return("A Book Title")

请参阅此答案以获取更多示例。将这些设置在适当的before :each块中,它们将在测试中拦截对gets的调用。

最新更新