Ruby indented multiline strings [duplicate]
Asked Answered
V

4

12

It's a best-practice question. There are obvious ways to do that, none of them just seem quite right.

Quite often I need to test that some multi-line string gets produced. This normally breaks indentation making everything look like a mess:

class TestHelloWorld < Test::Unit::TestCase
  def test_hello
    assert_equal <<EOS, hello_world
Hello, world!
  World greets you
EOS
  end
end

With <<- I can indent here doc marker, but it doesn't strip indentation inside heredoc, it still looks horrible.

class TestHelloWorld < Test::Unit::TestCase
  def test_hello
    assert_equal <<-EOS, hello_world
Hello, world!
  World greets you
    EOS
  end
end

This lets me indent but readability of test line suffers. This gsub really doesn't feel right here.

class TestHelloWorld < Test::Unit::TestCase
  def test_hello
    assert_equal <<-EOS.gsub(/^ {6}/, ""), hello_world
      Hello, world!
        World greets you
    EOS
  end
end

Is there any way to test such multi-line strings that's really readable?

Velma answered 28/7, 2010 at 7:13 Comment(1)
These two answers: https://mcmap.net/q/204457/-how-do-i-remove-leading-whitespace-chars-from-ruby-heredoc https://mcmap.net/q/204457/-how-do-i-remove-leading-whitespace-chars-from-ruby-heredoc might be alternatives to the accepted answer if you want to avoid external dependencies. They move the gsub out of sight by patching String, leaving the here string more readable.Electrothermics
T
7

Personally, I think that Ruby's indented heredocs are useless and they should work more like Bash indented heredocs and also strip whitespace inside the string …

Anyway, there are a couple of libraries that try to deal with this situation. There is a wide array of libraries that try to fix this problem:

Trim answered 28/7, 2010 at 8:15 Comment(0)
R
9

If you're building a Rails application, try using strip_heredoc, if not you could always require active_support core extensions.

Your Example might look like this:

require 'active_support/core_ext'

class TestHelloWorld < Test::Unit::TestCase
  def test_hello
    assert_equal <<-EOS.strip_heredoc, hello_world
      Hello, world!
        World greets you
    EOS
  end
end

If you really don't want to include them, the following code is copied from active_support as and example of how you might handle the formatting.

class String
  def try(*a, &b)
    if a.empty? && block_given?
      yield self
    else
      __send__(*a, &b)
    end
  end

  def strip_heredoc
    indent = scan(/^[ \t]*(?=\S)/).min.try(:size) || 0
    gsub(/^[ \t]{#{indent}}/, '')
  end
end
Rouault answered 22/4, 2013 at 15:15 Comment(0)
T
7

Personally, I think that Ruby's indented heredocs are useless and they should work more like Bash indented heredocs and also strip whitespace inside the string …

Anyway, there are a couple of libraries that try to deal with this situation. There is a wide array of libraries that try to fix this problem:

Trim answered 28/7, 2010 at 8:15 Comment(0)
C
0

I'm not sure any of these could be called "Best Practice" but here are four possibilities

class Hello

  def self.world
"Hello, world!
  World greets you
"
  end
end

require 'test/unit'

class TestHelloWorld < Test::Unit::TestCase

#Define a constant array of multiline strings and test against the array
# see test_hello_4 
# Alternatively store the multi-line strings in a Yaml fixture file and load 
# them into a constant Hash or Array within a setup method
MLINE = [
"Hello, world!
  World greets you
",
"Another multi line string",
  ]

  # Create a method to return the string
  def test_hello_1
    assert_equal Hello.world, hello_world_string()
  end

  # Create the string using embedded newlines
  def test_hello_2
    assert_equal Hello.world, "Hello, world!\n  World greets you\n"
  end

  # if you only have 1 in the test then put it in a DATA section
  def test_hello_3
    assert_equal Hello.world, DATA.read
  end

  def test_hello_4
    assert_equal Hello.world, MLINE[0]
  end

  def hello_world_string
"Hello, world!
  World greets you
"
  end
end

__END__
Hello, world!
  World greets you

All passing

Loaded suite test_hello_world
Started
....
Finished in 0.00083 seconds.

4 tests, 4 assertions, 0 failures, 0 errors

I would personally prefer the string with embedded newlines (Method 2) unless the string was very long in which case I would go with the DATA section.

Coachandfour answered 28/7, 2010 at 7:45 Comment(0)
L
0

Is it a test about formatting or about the content ?

If it's a test about formatting, maybe your test is too high level, and you should test a "Formatter" class and you'll probably find a way to test the class in a way that makes the multiline text comparison useless. And then, you would be able to mock the Formatter class to check that it will receive all the content it needs. For example, the Formatter could be a class that have a add_line method which adds a "\n" after each argument it is given and a formatted_string that will return the multiline string. Once you've tested the Formatter class, you'll just have to check it is called correctly. This way, you separate the tests for the content from the tests for the format.

If it's a test about the content, maybe you should just split the hello_world by line, and then check that the first line contains "Hello, world" and the second one contains "World greets you".

I don't think it's a good practice at all to test a whole multiline block of text.

Laurice answered 28/7, 2010 at 8:10 Comment(2)
Testing it all at once is the only right way. If it differs - test should show entire expected result, and entire actual result. Line by line comparisons and such just make test fail reports worthless.Velma
As I say in my answer, it really depends on what you are testing : the content or the format ? If you really want to test both at the same time, I think the others already have given good answers.Laurice

© 2022 - 2024 — McMap. All rights reserved.