DevLuke
DevLuke

Reputation: 93

Testing values of a JSON file with Rspec

I'm using Packer to create AMIs with baked in services. I know I can test the end product using serverspec, but I have a number of naming and tagging standards I'd like to enforce before the AMI is created. Such as version, OS, name etc. These values are held in a JSON file which is fed into packer during image creation.

My question is, is there a way to test/ pass in these values to Rspec and then use regex matcher to validate them. For example if I had in my variables.json

{"version: "0.1.0", "region": "eu-west-1"}

How could I check it using Rspecs regex matcher like

expect(region).to match(/^[a-z]{2}-[a-z]+-[0-9]$/)

Upvotes: 1

Views: 1155

Answers (1)

Alex Fortuna
Alex Fortuna

Reputation: 1243

I test such things by parsing JSON and then using the mighty include against resulting hashes. E.g. try this packed_json_spec.rb:

require "json"

describe "packed JSON data" do
  let(:input) {'{"version" : "0.1.0", "region" : "eu-west-1"}'}
  it "is valid" do
    h = JSON.parse(input)
    expect(h).to include("version" => match(/^\d+\.\d+\.\d+$/))
    expect(h).to include("region" => match(/^eu-\w+-\d+$/))
  end
end

Notes:

  1. Don't forget that RSpec is still Ruby.
  2. JSON means structure. So validity tests should cover structure as well as individual values.

Hope that was helpful. Cheers!

Upvotes: 1

Related Questions