Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby单元测试(gets.chomp)_Ruby_Unit Testing_Refactoring - Fatal编程技术网

Ruby单元测试(gets.chomp)

Ruby单元测试(gets.chomp),ruby,unit-testing,refactoring,Ruby,Unit Testing,Refactoring,我有ruby课程: class Sample def main zipcode = gets.chomp if correct_length?(zipcode) end end def correct_length?(string) true if string.size == 5 end end instance = Sample.new instance.main 并对其进行测试: require_relative 'sample'

我有ruby课程:

class Sample
  def main
    zipcode = gets.chomp

    if correct_length?(zipcode)
    end

  end

  def correct_length?(string)
    true if string.size == 5
  end
end

instance = Sample.new
instance.main
并对其进行测试:

require_relative 'sample'
require 'test/unit'

class TestSample < Test::Unit::TestCase
  def test_correct_length?
    zipcode = '10234'
    assert_equal(true, Sample.new.correct_length?(zipcode))
  end
end
需要相对的“样本”
需要“测试/单元”
类TestSample

我只想测试正确的长度?方法。当我运行测试时,我必须在测试开始之前输入一些字符。我应该如何重写这个示例来测试一个方法(不运行gets.chomp

在调用
main
的部分周围加上
if\uu FILE\uu==0。。。结束
;如果您运行测试,当脚本作为入口点执行时,该部分将不会执行

if __FILE__ == $0
  instance = Sample.new
  instance.main
end

将方法名称更改为
\u main
,以避免将来可能与顶级
self
发生冲突。我的理解是:运行测试时,必须先插入任何zipcode?如果是这样的话:将执行部分移动到另一个ruby文件中,在测试期间不需要该文件。如果我没有弄错的话,它们是在require_relative期间执行的,那么只需按照您已经完成的方式编写测试即可doing@TobiasSchoknecht我不想用方法分割文件。Falsetru anwser是对的。@ArupRakshit你能解释一下为什么我要把main换成_main吗?我是Ruby语言的新手。好吧,如果拆分不是一个选项,那么falsetru的答案可能是最好最简单的解决方案