2010-04-15 58 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