RSpec Scenario Outlines: Multiple Test Cases

2020-06-16 02:41发布

What's the best way to test a bunch of different test cases with RSpec?

For example, given 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

when I run rspec string-additions.rb --color --format doc, I get:

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

However, I'd like to get sensible output, like this:

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

And, I'd like to DRY up my specs a bit. Does RSpec provide a template for DRYing up this sort of multiple-case testing? Something similar to Cucumber scenario outlines?

Note: This question is similar to Is there an equivalent in RSpec to Cucumber's “Scenarios” or am I using RSpec the wrong way? but provides an example that should be tested with RSpec rather than Cucumber.

1条回答
狗以群分
2楼-- · 2020-06-16 03:26

After reading Elisabeth Hendrickson's Adventures with Auto-Generated Tests and RSpec, I came up with this solution:

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

This gives the output I want, but it'd be nicer if RSpec had a template to make things even DRYer.

查看更多
登录 后发表回答