RSpec场景概述:多个测试用例

ma1*_*w28 8 templates unit-testing rspec cucumber

使用RSpec测试一堆不同测试用例的最佳方法是什么?

例如,给定string-additions.rb:

require 'rspec'

class String
  if method_defined? :reverse_words
    raise "String#reverse_words is already defined"
  end
  def reverse_words
    split(' ').reverse!.join(' ')
  end
end

describe String do
  describe "#reverse_words" do
    specify { "hello".reverse_words.should eq("hello") }
    specify { "hello world".reverse_words.should eq("world hello") }
    specify { "bob & pop run".reverse_words.should eq("run pop & bob") }
  end
end
Run Code Online (Sandbox Code Playgroud)

当我跑步时rspec string-additions.rb --color --format doc,我得到:

String
  #reverse_words
    should == hello
    should == world hello
    should == run pop & bob
Run Code Online (Sandbox Code Playgroud)

但是,我希望获得合理的输出,如下所示:

String
  #reverse_words
    "hello" => "hello"
    "hello world" => "world hello"
    "bob & pop run" => "run pop & bob"
Run Code Online (Sandbox Code Playgroud)

而且,我想稍微干掉我的规格.RSpec是否提供了用于干预这种多案例测试的模板?类似黄瓜情景的概述

注意:这个问题类似于RSpec与Cucumber的"场景"中的等价物,还是我使用RSpec的方式错误?但提供了一个应该用RSpec而不是Cucumber测试的例子.

ma1*_*w28 10

在阅读了Elisabeth Hendrickson的自动生成测试和RSpec冒险之后,我想出了这个解决方案:

describe String do
  describe "#reverse_words" do
    strings = {
      "hello"         => "hello",
      "hello world"   => "world hello",
      "bob & pop run" => "run pop & bob"
    }

    strings.each do |k, v|
      specify "\"#{k}\" => \"#{v}\"" do
        k.reverse_words.should eq(v)
      end
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

这给出了我想要的输出,但是如果RSpec有一个模板可以让事情变得更干净,那就更好了.