Is it possible to have parameterized specs in RSpec?
Asked Answered
B

1

23

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.

Bord answered 23/1, 2011 at 18:53 Comment(0)
R
28

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
Renarenado answered 23/1, 2011 at 19:0 Comment(1)
The humble #each technique is very effective! I made a small DSL to make parameterized testing with RSpec a bit more convenient: github.com/odlp/rspec-with_params (it allows multiple parameters, and prints out each group with a "given a => b, x => y, " context for clarity)Cullender

© 2022 - 2024 — McMap. All rights reserved.