Last Updated: March 02, 2016
·
1.351K
· volontarian

RSpec: compare rendered text like HTML or XML in view specs

I created some helper methods for RSpec which help you compare rendered text without checking each DOM element by xpath or css selectors.

You can use them like this:

describe 'example.html.erb' do
  it 'renders HTML like this' do
    render

    # looks for spec/fixtures/example.html
    compare_texts rendered, 'example.html'
  end
end

Fixtures can be initialized by passing preview option with true:

# will create or override file spec/fixtures/example.html
compare_texts rendered, 'example.html', true

This is the helper code which you can put in a .rb file under spec/support:

def compare_texts(got_string, expected_fixture_path, preview = false)
  if preview
    absolute_path = File.join(File.dirname(__FILE__), "../fixtures/#{expected_fixture_path.split('/')[0..-2].join('/')}")
    FileUtils::mkdir_p absolute_path
    File.open("#{absolute_path}/#{expected_fixture_path.split('/')[-1]}", 'w') { |file| file.write(got_string) }
    puts "#{expected_fixture_path} created."
  else
    expect(strip_text(got_string)).to be == strip_text(load_fixture(expected_fixture_path))
  end
end

def load_fixture(path)
  path = File.join(File.dirname(__FILE__), "../fixtures/#{path}")
  File.open(path).read
end

def strip_text(text, remove_empty_lines = true)
  text = text.strip.split("\n").map(&:strip)

  text.delete_if{|line| line == '' } if remove_empty_lines

  text.join("")
end

P.S.: You can use e.g. http://diffchecker.com for comparison of expected and got text if example fails.

2 Responses
Add your response

Awesome, will it be a gem?

over 1 year ago ·

I won't release a gem for this less code yet. Putting it in a file under spec/support like coderwall.com also does should be a good place and maintainable: https://github.com/assemblymade/coderwall/blob/master/spec/support/fixture_helper.rb

over 1 year ago ·