我有ruby script在运行时从用户那里获取图书的价格。我是为Ruby脚本编写RSpec测试的新手。我使用的是Ruby 1.9.3-p327和rspec 2.11.0。您可以从 Github this link 克隆我的项目。
我的Rspec测试旨在测试新实例化的对象是否属于特定类。
如果我在ruby script中注释第32行,我的测试成功通过。
当我取消注释该行时,我收到的错误与用户输入有关。我甚至没有将此作为spec file的一部分进行测试,但我仍然登陆此错误。我不确切地知道为什么以及如何解决这个问题。
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,但我主要关注如何测试属于哈希的多个元素的用户输入< / p>
感谢。
答案 0 :(得分:0)
使用
STDIN.gets.chomp
请参阅this answer。
测试此方法的最佳方法是使用返回预设响应的对象和方法来模拟IO#gets
。 RSpec模拟看起来像:
STDIN.should_receive(:gets).and_return("A Book Title")
有关更多示例,请参阅this answer。在适当的before :each
块中设置这些内容,它们会拦截您测试中对gets
的调用。