【发布时间】:2011-03-22 00:11:53
【问题描述】:
这是一个最佳实践问题。有很明显的方法可以做到这一点,但没有一个看起来完全正确。
我经常需要测试是否生成了一些多行字符串。这通常会破坏缩进,使一切看起来一团糟:
class TestHelloWorld < Test::Unit::TestCase
def test_hello
assert_equal <<EOS, hello_world
Hello, world!
World greets you
EOS
end
end
使用<<-,我可以在此处缩进文档标记,但它并没有去除heredoc内部的缩进,它看起来仍然很糟糕。
class TestHelloWorld < Test::Unit::TestCase
def test_hello
assert_equal <<-EOS, hello_world
Hello, world!
World greets you
EOS
end
end
这让我可以缩进,但测试行的可读性会受到影响。这个gsub 真的不在这里。
class TestHelloWorld < Test::Unit::TestCase
def test_hello
assert_equal <<-EOS.gsub(/^ {6}/, ""), hello_world
Hello, world!
World greets you
EOS
end
end
有没有办法测试这种真正可读的多行字符串?
【问题讨论】:
-
如果您想避免外部依赖,这两个答案:stackoverflow.com/a/3772911/17305 stackoverflow.com/a/5638187/17305 可能是已接受答案的替代方案。他们通过修补
String将gsub移出视线,使此处的字符串更具可读性。
标签: ruby code-formatting