Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested Context Blocks in RSpec

Tags:

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
like image 206
Jackson Avatar asked Oct 31 '15 02:10

Jackson


People also ask

Is it possible to nest describe blocks in RSpec?

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...

What is context in RSpec?

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.

What is let in Ruby?

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.


2 Answers

Although this is an old question, I'm going to post another answer in here for two reasons:

  1. This is the top Google result for almost anything related to RSpec context nesting.

  2. 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.

like image 123
Carlos I. García Avatar answered Oct 13 '22 01:10

Carlos I. García


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.

like image 27
K M Rakibul Islam Avatar answered Oct 13 '22 00:10

K M Rakibul Islam