2011-04-02 50 views
8

用RSpec测试一堆不同测试用例的最佳方法是什么?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 

当我运行rspec string-additions.rb --color --format doc,我得到:

String 
    #reverse_words 
    should == hello 
    should == world hello 
    should == run pop & bob 

不过,我想获得合理的输出,这样的:

String 
    #reverse_words 
    "hello" => "hello" 
    "hello world" => "world hello" 
    "bob & pop run" => "run pop & bob" 

而且,我想DRY上我的规格了一下。 RSpec是否提供了用于干这种多案例测试的模板?类似于Cucumber scenario outlines

注意:此问题与Is there an equivalent in RSpec to Cucumber's “Scenarios” or am I using RSpec the wrong way?类似,但提供了一个应使用RSpec而不是Cucumber进行测试的示例。

回答

9

阅读Elisabeth Hendrickson's Adventures with Auto-Generated Tests and 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 

这给了我想要的输出,但它会是更好,如果有RSpec的模板,使事情变得机。