Rspec中describe和context不同

转自  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() 的行为,导致一个结果,如果只关注一个这个状态时,火箭的启动结果,就不需要再看其他状态的代码

 

posted on 2016-02-10 16:55  c3tc3tc3t  阅读(1118)  评论(0编辑  收藏  举报