rubyrspectddrspec2rspec3

Is it possible to have parameterized specs in RSpec?


If I have a spec that needs to be run with different values to have it drive a real implementation and not a naive one. An example:

it "should return 'fizz' for multiples of three" do  
  @fizzbuzz.get_value(3).should == "fizz"
end

So far I haven't found any way to pass 3 in as a parameter. The spec below solves my problem but I'm wondering if it's the recommended way to do it or if there is any other, better way.

it "should return 'fizz' for multiples of three" do  
  [3, 6].each{|number| @fizzbuzz.get_value(number).should == "fizz" }
end

I don't like this because it uses loops, it's not readable and it only shows up as one spec when run, I would rather have it show up as two different tests.


Solution

  • To generate separate tests you could do:

    [3, 6].each do |num|
      it "should return 'fizz' for multiples of three (#{num})" do  
        @fizzbuzz.get_value(num).should == "fizz"
      end
    end
    

    Because spec files are simple run as ruby scripts you can use all the standard ruby constructs to generate tests on the fly.

    Even better you can use Numeric#step to easily generate a certain range of tests, e.g. for [3, 6, 9, 12, 15, 18]:

    3.step(18, 3) do |num|
      it "should return 'fizz' for multiples of three (#{num})" do  
        @fizzbuzz.get_value(num).should == "fizz"
      end
    end