ogirginc
ogirginc

Reputation: 5270

New line error for Redcarpet gem

I have a #markdown method in my ApplicationHelper that I wanted write a simple unit test:

def markdown(text)
  markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML)
  markdown.render(text).html_safe # tried wihout html_safe too
end

Whenever I wrote a RSpec test, it kept failing. I tried it with three different ways:

expect(helper.markdown('# Header')).to eq('<h1>Header</h1>')
# => expected: "<h1>Header</h1>" but got: "<h1>Header</h1>\n"

expect(helper.markdown('# Header')).to eq('<h1>Header</h1>\n')
# => expected: "<h1>Header</h1>\\n" got: "<h1>Header</h1>\n"

expect(helper.markdown('# Header').delete_suffix('\n')).to eq('<h1>Header</h1>')
# => expected: "<h1>Header</h1>" got: "<h1>Header</h1>\n"

How can I make this unit test pass?

Ruby 2.5.1 | Rspec 3.7.0 | Rails 5.2 | Redcarpet 3.4

Upvotes: 0

Views: 260

Answers (1)

matt
matt

Reputation: 79723

The sequence \n is only parsed as an escape code for a newline when it is between double quotes: "\n". In single quotes it is just a literal \ and a literal n.

To get the test to pass you just need to use double quotes in the string with the \n:

expect(helper.markdown('# Header')).to eq("<h1>Header</h1>\n")

Upvotes: 1

Related Questions