0

I have written the serverspec resource type below for checking if keys have the right values for some YAML configuration files I have For each key in the hash table I assign an attribute on the resource type instance. If a key does not exist I'd like to fail with the appropriate message.
After digging up in rspec's code I found that if I mixin the RSpec::Expectations module I can call fail_with() which should report that the test fails. However I'm getting a SystemStackError from the line that calls fail_with() that says "stack level too deep". I'm guessing that I'm doing it wrong. Is there a way to make the test fail with a message that makes sense?

require 'yaml'

module Serverspec
  module Type

    class YAMLFile < Base
      include RSpec::Expectations

      def initialize(path)
        yaml = YAML.load_file(path)
        return unless yaml

        yaml.each { |key, value| self.send('#{key}=', value) }
      end

      def method_missing(m, *args, &block)
        # fail here with message
        self.fail_with('The key does not exist in the YAML file')
      end
    end

    def yaml_file(path)
      YAMLFile.new(path)
    end
  end
end

include Serverspec::Type
the_drow
  • 18,571
  • 25
  • 126
  • 193

1 Answers1

0

The solution is to use the fail() method instead of fail_with(). I still don't know why I can't use fail_with() though. Here's the working code for future reference:

require 'yaml'

module Serverspec
  module Type

    class YAMLFile < Base
      def initialize(path)
        yaml = YAML.load_file(path)
        return unless yaml

        yaml.each { |key, value| self.send('#{key}=', value) }
      end

      def method_missing(m, *args, &block)
        fail "The key '%s' does not exist in the YAML document" % m
      end
    end

    def yaml_file(path)
      YAMLFile.new(path)
    end
  end
end

include Serverspec::Type
the_drow
  • 18,571
  • 25
  • 126
  • 193