views:

30

answers:

2

I am trying to write a spec were the number of examples i.e. 'it "should ..." do' are determined at runtime. I tried putting the 'it' method in my own method so that I could call it multiple times:

def new_method(test)  
    it "#{test} should... " do  
    end  
end  

However, the 'it' method is not available from the current Spec::Example::ExampleGroup::Subclass instance.

+2  A: 

To avoid code duplication, sometimes I do something like this:

describe SomeOjbect do
  %w(a b c d e f g).each do |val|
    it "should have a value of #{val}" do
      # ...
    end
  end
end

Which would create 7 examples in the spec. I suppose if you really were dead-set on using a method, you could do something like this:

def new_method(grp, test)
  grp.instance_eval do
    it "#{test} should..." do
      # ...
    end
  end
end

describe SomeObject do
  new_method(self, "a")
  new_method(self, "b")
  new_method(self, "c")
  new_method(self, "d")
  # ...
end

Here you pass self, which is the scope of the describe block, and instance_eval lets you execute code as if you were in that block, so the it method is available.

rspeicher
Thanks for your quick response. Thanks for the examples. They work if you know at development time how many examples you need to run. Unfortunately, in my case, I need to determine this at runtime.
Kerry
Well I also described how to make your `new_method` idea work.
rspeicher
A: 

http://github.com/dchelimsky/rspec/wiki/FAQ#dynamic_specs

rogerdpack
Thanks for your quick response. Thanks for the examples. They work if you know at development time how many examples you need to run. Unfortunately, in my case, I need to determine this at runtime.
Kerry