0

我在下面编写了 serverspec 资源类型,用于检查键是否具有我拥有的某些 YAML 配置文件的正确值。对于哈希表中的每个键,我在资源类型实例上分配一个属性。如果密钥不存在,我希望失败并显示相应的消息。
在挖掘 rspec 的代码后,我发现如果我混合RSpec::Expectations模块,我可以调用fail_with()它应该报告测试失败。但是,我SystemStackError从调用fail_with()“堆栈级别太深”的行中得到了一个。我猜我做错了。有没有办法通过一条有意义的消息使测试失败?

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
4

1 回答 1

0

解决方案是使用fail()方法而不是fail_with(). 我仍然不知道为什么我不能使用fail_with()。这是供将来参考的工作代码:

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
于 2015-10-08T07:34:47.863 回答