如何在运行时向rspec添加示例?

0 ruby rspec runtime dynamic

我试图编写一个规范的例子,即'it'应该......"do"是在运行时确定的.我尝试将'it'方法放在我自己的方法中,以便我可以多次调用它:

def new_method(test)  
    it "#{test} should... " do  
    end  
end  
Run Code Online (Sandbox Code Playgroud)

但是,'it'方法不能从当前的Spec :: Example :: ExampleGroup :: Subclass实例中获得.

Rob*_*her 5

为避免代码重复,有时候我会这样做:

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
Run Code Online (Sandbox Code Playgroud)

这将在规范中创建7个示例.我想如果你真的死定了使用方法,你可以做这样的事情:

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
Run Code Online (Sandbox Code Playgroud)

在这里传递self,这是describe块的范围,并instance_eval允许您执行代码,就像您在该块中一样,因此该it方法可用.