Rspec中describe和context不同

c3tc3tc3t發表於2016-02-10

轉自  http://lmws.net/describe-vs-context-in-rspec

學習rspec,不太理解describe和context。google了一下,找到這篇文章,感覺說的有些道理

1 在Rspec的世界裡,我們經常看到人們使用descirbe程式碼塊和context程式碼塊 例如

1 describe "launch the rocket" do
2   context "all ready" do
3   end
4  
5   context "not ready" do
6   end
7 end

那麼context和descript有啥不同呢

According to the rspec source code, “context” is just a alias method of “describe”, meaning that there is no functional difference between these two methods. However, there is a contextual difference that’ll help to make your tests more understandable by using both of them.

說的是,按照rspec原始碼來看,context僅僅是describe方法的別名,意味著這兩者沒有任何功能性的不同, 然而有一些語境不同(語義不同),理解這個能讓你寫出更可讀的程式碼

 

The purpose of “describe” is to wrap a set of tests against one functionality while “context” is to wrap a set of tests against one functionality under the same state. Here’s an example

describe的目的是當它包裹一組,一個功能,的測試程式碼

context的目的是包裹一組,同一狀態下,一個功能的,測試程式碼

 

例如下面程式碼

 1 describe "launch the rocket" do
 2   before(:each) do
 3     #prepare a rocket for all of the tests
 4     @rocket = Rocket.new
 5   end
 6  
 7   context "all ready" do
 8     before(:each) do
 9       #under the state of ready
10       @rocket.ready = true
11     end
12  
13     it "launch the rocket" do
14       @rocket.launch().should be_true
15     end
16   end
17  
18   context "not ready" do
19     before(:each) do
20       #under the state of NOT ready
21       @rocket.ready = false
22     end
23  
24     it "does not launch the rocket" do
25       @rocket.launch().should be_false
26     end
27   end
28 end

上面的程式碼可讀性好在,沒有將所有東西都用describe包裹,因為你讀測試程式碼是在context語境內,對於一個context設定一個物件狀態,

@rocket.ready為true時, @rocket.launch() 的行為,導致一個結果,如果只關注一個這個狀態時,火箭的啟動結果,就不需要再看其他狀態的程式碼

 

相關文章