Add Specs for Yaml files

* Add spec/support folder

* Add YamlSortChecker to check if yaml files are sorted

* Add Diffy as a development dependency

* Add spec file for all yaml config files for sorting
This commit is contained in:
Ace Dimasuhid 2017-07-09 23:55:43 +08:00
parent 52819d3e93
commit 8a8473e73a
3 changed files with 92 additions and 0 deletions

View file

@ -29,4 +29,5 @@ Gem::Specification.new do |spec|
spec.add_development_dependency 'rake'
spec.add_development_dependency 'rspec'
spec.add_development_dependency 'rubocop'
spec.add_development_dependency 'diffy'
end

View file

@ -0,0 +1,53 @@
require 'yaml'
require 'diffy'
# Check Yaml if Alphabetically sorted
class YamlSortChecker
class NotSortedError < StandardError; end
def initialize(filename)
@yaml = YAML.load_file(filename)
end
def sorted?(type = :key)
case type.to_sym
when :key then key_sorted?
when :value then value_sorted?
end
true
end
private
attr_reader :yaml
def key_sorted?
sorted_yaml = yaml.to_a.sort_by { |content| content[0].downcase }
different_from_yaml? sorted_yaml
end
def value_sorted?
sorted_yaml = yaml.to_a.sort_by do |content|
[content[1].downcase, content[0].downcase]
end
different_from_yaml? sorted_yaml
end
def different_from_yaml?(sorted_yaml)
actual_str = enum_to_str(yaml)
expected_str = enum_to_str(sorted_yaml)
difference = Diffy::Diff.new(actual_str, expected_str).to_s
return if difference.empty?
raise NotSortedError, "\n#{difference}"
end
def enum_to_str(enum)
enum.to_a.map { |x| x.join(' ') }.join("\n")
end
end

38
spec/yaml_spec.rb Normal file
View file

@ -0,0 +1,38 @@
require 'spec_helper'
require 'support/yaml_sort_checker.rb'
RSpec.describe 'Yaml files' do
let(:base_directory) { 'lib/yaml' }
describe 'file_aliases.yaml' do
let(:checker) { YamlSortChecker.new("#{base_directory}/file_aliases.yaml") }
it 'is sorted correctly' do
expect(checker.sorted?(:value)).to eq true
end
end
describe 'folder_aliases.yaml' do
let(:checker) { YamlSortChecker.new("#{base_directory}/folder_aliases.yaml") }
it 'is sorted correctly' do
expect(checker.sorted?(:value)).to eq true
end
end
describe 'folders.yaml' do
let(:checker) { YamlSortChecker.new("#{base_directory}/folders.yaml") }
it 'is sorted correctly' do
expect(checker.sorted?).to eq true
end
end
describe 'files.yaml' do
let(:checker) { YamlSortChecker.new("#{base_directory}/files.yaml") }
it 'is sorted correctly' do
expect(checker.sorted?).to eq true
end
end
end