Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec Scenario Outlines: Multiple Test Cases

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.

like image 229
ma11hew28 Avatar asked Apr 02 '11 15:04

ma11hew28


1 Answers

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.

like image 167
ma11hew28 Avatar answered Oct 18 '22 08:10

ma11hew28