rspec / minitest for Ruby:如何将对象数组转换为单独的测试?

时间:2015-06-07 00:27:10

标签: ruby json rspec minitest

我正在为一种小型语言编写解析器,该语言具有以JSON格式化的测试规范,实际上是这样的:

[ {"input":"foo", "output":"bar"}, 
  {"input":"baz", "output":"boo"},
  ...]

假设我已将JSON解析为哈希数组,我将如何编写一个使用input作为描述符的规范并针对每个output测试我的库?

1 个答案:

答案 0 :(得分:2)

简单地遍历哈希。你有几个选择:

inputs_and_outputs = [
  { 'input' => 'a', 'output' => 'x' },
  { 'input' => 'b', 'output' => 'y' }
]

标准Minitest

# One test with multiple assertions
def test_that_it_returns_the_expected_outputs
  inputs_and_outputs.each do |input_output|
    input = input_output['input']
    output = input_output['output']

    assert_equal output, your_function(input)
  end
end


# Separate test per input output
inputs_and_outputs.each do |input_output|
  input = input_output['input']
  output = input_output['output']

  define_method("test_returns_#{output}_given_#{input}") do
    assert_equal output, your_function(input)
  end
end

Minitest Spec

# One test with multiple assertions
it "returns the expected outputs" do
  inputs_and_outputs.each do |input_output|
    input = input_output['input']
    output = input_output['output']

    assert_equal output, your_function(input)
  end
end

# Separate test per input output
inputs_and_outputs.each do |input_output|
  input = input_output['input']
  output = input_output['output']

  it "returns #{output} given #{input}" do
    assert_equal output, your_function(input)
  end
end