Does it seem bad to be nesting context blocks inside of other context blocks?
For example:
describe "update_management" do
context "with a typical update" do
context "when a red flag has been raised" do
it "" do
end
end
context "when a yellow flag has been raised" do
it "" do
end
end
etc...
end
end
You CAN nest contexts in RSpec and they will work. The issue is that it is a somewhat polarized topic, and some people will rather stay away from it. Some people will tell you it's a good practice, others will tell you it's not...
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.
Use let to define a memoized helper method. The value will be cached across multiple calls in the same example but not across examples. Note that let is lazy-evaluated: it is not evaluated until the first time the method it defines is invoked.
Although this is an old question, I'm going to post another answer in here for two reasons:
This is the top Google result for almost anything related to RSpec context nesting.
The only other answer here points to BetterSpecs, which doesn't explicitly tackle the issue, and also has no search capability... yet.
You CAN nest contexts in RSpec and they will work. The issue is that it is a somewhat polarized topic, and some people will rather stay away from it. Some people will tell you it's a good practice, others will tell you it's not... there's no real consensus AFAIK.
Honestly, if nesting contexts works for your use case, by all means go and do it. The important thing is that your context descriptors make sense even when nested, which by the way is also a polarized topic, as you can see in this issue that's been open for over half a year (as of today).
Although BetterSpecs is a great source of information it either falls short in providing example cases and/or doesn't dumb things down enough for some people (like me). I like Jake Goulding's explanations as a compliment to these docs a lot, you should check it out.
I strongly recommend that you check out Better Specs to know more about the best practices while using contexts
in your RSpec tests. You can also take a look at the rspec-style-guide to know more about best practices.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With