Last active
August 29, 2015 14:16
-
-
Save volontarian/1dd0f01f13e09c848394 to your computer and use it in GitHub Desktop.
RSpec: compare rendered text like HTML or XML (use diffchecker.com for comparison of expected and got text if example fails)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
describe 'example.html.erb' do | |
it 'renders HTML like this' do | |
render | |
compare_texts rendered, 'example.html' | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment