In Rspec world, you often see people using both “describe” blocks and “context” blocks together, like this
describe "launch the rocket" do context "all ready" do end context "not ready" do end end
So what’s the difference between “describe” and “context” really?
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.
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 "launch the rocket" do before(:each) do #prepare a rocket for all of the tests @rocket = Rocket.new end context "all ready" do before(:each) do #under the state of ready @rocket.ready = true end it "launch the rocket" do @rocket.launch().should be_true end end context "not ready" do before(:each) do #under the state of NOT ready @rocket.ready = false end it "does not launch the rocket" do @rocket.launch().should be_false end end end
This code is more readable than wrapping all the stuffs with “describe” blocks. Because when you read the tests under “context”, you know they are all testing the same thing the “describe” talk about. And you know a “context” is to setup the state of your object, in this case @rocket.ready which will effects the behavior of @rocket.launch() that gives you a conclusion, right away, without scanning the code back and forth.
13 responses to “describe vs. context in rspec”
[…] 그래서 구글에 이것에 대해 물었고, 이것을 발견했습니다 : describe vs. context in rspec , 그 대답은 꽤 흥미 […]
Amazing, I’ve wanted to know about this for so long. Thank you!
thank you for share.
Excellent! Thanks for share!
Good article) Finally I understood difference between ‘describe’ and ‘context’. Thanks)
Good ! I got it
Thank’s a lot for that terse clear explanation!
Yes, in case you use rspec as acceptance/integration tests framework.
I think a more accurate definition of “individual scenarios” is the scenarios to test the same functionality under different states of the system.
^^ for integration or request specs that is.
I was wondering how others were using context, so this is insightful, thanks.
Another way of illustrating their relationship would be to use “describe” to wrap the user story and the “context” to wrap individual scenarios.
yes, you are right. it’s a typo, thanks
You wrote, but I think you meant ““context” is just a alias method of “describe””. Yes?
Saved, I love your blog! :)