简体   繁体   English

Ruby-如何使用Minitest测试方法

[英]Ruby - how to test method using minitest

I have this class: 我有这个课:

require 'yaml'

class Configuration
  class ParseError < StandardError; end

  attr_reader :config

  def initialize(path)
    @config = YAML.load_file(path)
  rescue => e
    raise ParseError, "Cannot open config file because of #{e.message}"
  end

  def method_missing(key, *args, &block)
    config_defines_method?(key) ? @config[key.to_s] : super
  end

  def respond_to_missing?(method_name, include_private = false)
    config_defines_method?(method_name) || super
  end

  private

  def config_defines_method?(key)
    @config.has_key?(key.to_s)
  end
end

how do I write test for methods: method_missing, respond_to_missing?, config_defines_method? 如何编写方法测试:method_missing,response_to_missing,config_defines_method? I have some understanding about unit testing but when it comes to Ruby im pretty new. 我对单元测试有一定的了解,但是对于Ruby来说,它是非常新的。

So far i have tried this: 到目前为止,我已经尝试过了:

def setup
  @t_configuration = Configuration.new('./config.yaml')
end

def test_config_defines_method
  @t_configuration.config[:test_item] = "test"
  assert @t_configuration.respond_to_missing?(:test_item)
end

Im not sure if im testing it right, because when i run rake test it gives me this: 我不确定即时测试是否正确,因为当我运行rake test时,它给了我:

NoMethodError: private method `respond_to_missing?' NoMethodError:私有方法`respond_to_missing?' called for # 要求 #

If there is no clear way how to solve this, can anyone direct me to a place where similar tests are written? 如果没有明确的方法来解决此问题,有人可以将我引导到编写类似测试的地方吗? So far Ive only found hello world type of test examples which are not helping much in this case. 到目前为止,我只发现了hello世界类型的测试示例,在这种情况下并没有太大帮助。

As mentioned in the documentation for #respond_to_missing? #respond_to_missing?文档中#respond_to_missing? , you do not want to call the method directly. ,您不想直接调用该方法。 Instead, you want to check that the object responds to your method. 相反,您要检查对象是否响应您的方法。 This is done using the #respond_to? 使用#respond_to?完成#respond_to? method: 方法:

assert @t_configuration.respond_to?(:test_item)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM