2010-04-15 53 views
7

rspec方法是否可能获取在本地方法中传递给它的参数的值?例如,如果我想:rspec“它”字符串

describe Me do 
    it "should figure this out" 
    puts "I " + SPEC_NAME 
    end 
end 

打印此:

I should figure this out 

...什么将我的代码示例中放了SPEC_NAME?

更好的是,像我这样的一个相对较新的垃圾邮件专家怎么能自己想出来呢?

回答

7

description方法应该做你想做的。例如

describe Me do 
    it "should figure this out" do 
    puts "I " + description # or "I #{description}" using string interpolation 
    end 
end 

在如何算出这个方面,我发现它通过查看RDocs for RSpec,通过查看it方法的源代码,看看它是如何工作的开始。然后您会发现RSpec将“it”字符串引用为“description”,因此您可以查找包含其名称中的说明的可用方法。

我知道现在对你没有太大的用处,但是当你学习更多的Ruby时,你会发现它更容易阅读像RSpec这样的库中的代码,并且会发展出一种本能来实现它们,将帮助你在正确的地方寻找东西。

+0

这是完美的,谢谢! – lambinator 2010-04-15 17:13:37

+1

我试过用RSpec 2.8.0,但没有马上工作。这是在运行什么对象?我发现:RSpec :: ExampleGroup :: Nested_2(我想这是你的ExampleGroup)对于我来说,解决方案是:example.description – inger 2012-05-01 19:53:01

+0

+1包含关于如何从源文件中找出类似事情的说明。 – ErJab 2013-09-30 23:26:23

0

这不回答你的问题完全是,但是如果你想打印出每个测试的运行,把这个在您的spec.opts文件:
--format specdoc

以下是对我的测试看一个例子就像当我运行它们:

A new release when parsing the artist containing a full join word 
- should remove it 
- should not remove it when it is inter-word 

A new release when parsing the artist containing an abbreviated joining word 
- should remove it when there is a period after it 
- should remove it when when there is not a period after it 
- should not remove it when it is inter-word with a period after it 
- should not remove it when it is inter-word without a period after it 

A new release when parsing the artist 
- should be invalid if the year is not current 
- should be valid if it is the current year 
+0

不是我一直在寻找的,但很棒的提示! – lambinator 2010-04-15 17:14:03

1

对于较新的RSpec版本(我使用的是2.14),你可以称其为example.description

it "prints itself" do 
    puts "My description string is '#{example.description}'." 
end