Breedly
Breedly

Reputation: 14256

Test an ERB Template

I've written a template that does some stuff to a JSON object, as an example:

{
  "list": [
    <% ['a', 'b', 'c', 'd'].each do |letter| %>
     <%= puts "{ \"letter\": \"" + letter + "\" }," %>
    <% end %>
   ]
}

How can I write a unit test to check if the JSON output is valid? I'm new to Ruby so I don't really know the tools I would use for this. Also, is there a better way to make a list of JSON objects in an ERB template?

I don't have access to, or knowledge of the thing that's processing the template so I'm not really positive about which Ruby libraries I can consume.

NOTE: RAILS is not involved. Just vanilla Ruby.

Upvotes: 1

Views: 2116

Answers (1)

Cara McCormack
Cara McCormack

Reputation: 402

If you are just trying to return some object or list as JSON, you can call render json: object from your controller. You can test this the same way you can test any other controller: http://guides.rubyonrails.org/testing.html#functional-tests-for-your-controllers

If you absolutely need it in ERB for whatever reason, you can call the .to_json method on the object between ERB tags: <%= object.to_json %>.

The .to_json method will always return valid JSON.

Upvotes: 1

Related Questions