简体   繁体   中英

How can I add examples to rspec at runtime?

I am trying to write a spec were the number of examples ie '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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM