Debian Codegraph @

test/spec_test.rb

raw symbols SCIP
1 require 'mustache'
2 require 'tmpdir'
3 require 'yaml'
4 require 'minitest/autorun'
5
6 # Calls appropriate method on YAML. See: https://gist.github.com/tenderlove/958999ab4240b93bd3cd
7 YAML.add_domain_type(nil, 'code') { |_, val| eval(val['ruby']) }
8
9 # A simple base class for Mustache specs.
10 # Creates a partials directory, then points a (dynamic) subclass of Mustache at
11 # that directory before each test; the partials directory is destroyed after
12 # each test is run.
13 class MustacheSpec < Minitest::Test
14 def setup
15 @partials = File.join(File.dirname(__FILE__), 'partials')
16 Dir.mkdir(@partials)
17
18 @Mustache = Class.new(Mustache)
19 @Mustache.template_path = @partials
20 end
21
22 def teardown
23 Dir[File.join(@partials, '*')].each { |file| File.delete(file) }
24 Dir.rmdir(@partials)
25 end
26
27 # Extracts the partials from the test, and dumps them into the partials
28 # directory for inclusion.
29 def setup_partials(test)
30 (test['partials'] || {}).each do |name, content|
31 File.open(File.join(@partials, "#{name}.mustache"), 'w') do |f|
32 f.print(content)
33 end
34 end
35 end
36
37 # Asserts equality between the rendered template and the expected value,
38 # printing additional context data on failure.
39 def assert_mustache_spec(test)
40 actual = @Mustache.render(test['template'], test['data'])
41
42 assert_equal test['expected'], actual, "" <<
43 "#{ test['desc'] }\n" <<
44 "Data: #{ test['data'].inspect }\n" <<
45 "Template: #{ test['template'].inspect }\n" <<
46 "Partials: #{ (test['partials'] || {}).inspect }\n"
47 end
48
49 def test_noop; assert(true); end
50 end
51
52 spec_files = File.join(File.dirname(__FILE__), '..', 'ext', 'spec', 'specs', '*.yml')
53 Dir[spec_files].each do |file|
54 spec = YAML.load_file(file)
55
56 klass_name = "Test" + File.basename(file, ".yml").sub(/~/, '').capitalize
57 instance_eval "class ::#{klass_name} < MustacheSpec; end"
58 test_suite = Kernel.const_get(klass_name)
59
60 test_suite.class_eval do
61 spec['tests'].each do |test|
62 define_method :"test_spec - #{test['name']}" do
63 setup_partials(test)
64 assert_mustache_spec(test)
65 end
66 end
67 end
68 end