21

Why this yaml file won't parse?

---
<% sensor_types = YAML.load_file('db/seed-fixtures/sensor_type.yml') %>
<% sensor_types.each do |sensor_type| %>
sensor<%= sensor_type['id'] %>:
  id: <%= sensor_type['id'] %>
  title: <%= sensor_type['title'] %>
  unit: "<%= sensor_type['unit'] %>"
  valid_min: <%= sensor_type['valid_min'] %>
  valid_max: <%= sensor_type['valid_max'] %>
  codename: <%= sensor_type['codename'] %>
  scale_base_ten_exponent: <%= sensor_type['scale_base_ten_exponent'] %>
<% end %>

this file is used for fixtures in my tests, it is loaded by rspec from the fixtures directory.

when I try it I get: "mapping values are not allowed in this context at line 4 column 28 (Psych::SyntaxError)"

kirlev
  • 680
  • 1
  • 7
  • 17
  • How do you load this file? Do you use it as a generic yaml file or do you load it as an ERB file and then parse it as yaml? – Dimitri Aug 04 '14 at 09:26
  • I edited the question to answer your question, I think Rspec load it as yaml. – kirlev Aug 04 '14 at 09:37
  • Can you provide a test yaml file with that error line? Also, did you try to load with the syck gem yet instead of Psych? gem install syck, then require 'yaml', then require 'syck', and then YAML::ENGINE.yamler = 'syck' and then you load the yaml file – shevy Aug 04 '14 at 09:40

1 Answers1

49

You can't load a YAML file containing ERB like a basic YAML file. Checkout this post.

What you can do instead is (in a spec initializer or a before hook):

FIXTURE_CONFIG = YAML.load(ERB.new(File.read("#{Rails.root}/path_to_your_file.yml.erb")).result)

And then use this variable in your test.

Gabriel
  • 1,253
  • 13
  • 16
Dimitri
  • 2,023
  • 18
  • 23
  • 2
    I'm using this YAML file for fixtures so it's actually does the ERB rendering as stated in the post you linked. but your code helped me debug the file and figure that the problem was with the source yaml I was loading. thanks. – kirlev Aug 05 '14 at 11:38