8

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 Answer 1

11

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.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.