rspec"它"字符串

lam*_*tor 7 ruby rspec

是否有可能rspec方法获取在本地方法中传递给it()的参数的值?例如,如果我想:

describe Me do
  it "should figure this out"
    puts "I " + SPEC_NAME
  end
end
Run Code Online (Sandbox Code Playgroud)

打印这个:

I should figure this out
Run Code Online (Sandbox Code Playgroud)

...我会在代码示例中为SPEC_NAME提供什么?

更好的是,像我这样的一位相对新的Rubologist怎么会自己解决这个问题呢?

mik*_*kej 7

description方法应该做你想要的.例如

describe Me do
  it "should figure this out" do
    puts "I " + description # or "I #{description}" using string interpolation
  end
end
Run Code Online (Sandbox Code Playgroud)

在如何解决这个问题方面,我通过查看RSpecRSoc来找到它,首先查看it方法的来源,看看它是如何工作的.然后,您将发现RSpec将"it"字符串称为"描述",因此您可以查找其名称中包含描述的可用方法.

我知道它现在对你没什么用处,但随着你学到更多Ruby,你会发现更容易阅读像RSpec这样的库中的代码,并会发展出一种可能实现它们的本能,这将有助于你看在适当的地方做事.