Describe vs context in Rspec

Rspec tests are grouped inside describe block. I assume this provides the context for the humans reading the test code and helps in organizing the code (like we can have a ‘before’ block and have a set of common code to be run for each test).

describe "homepage"
  
  before(:each) do 
    ## write some common code for this 'describe'
  end
  
  it "has title" do
    ## write the actual test code here.
  end

  it "has subtitle" do
    ## write another test code here.
  end
end

I understand this. Also I noticed that describe can be nested. So I can have describe block for navigation that is inside the describe of the home page.

Then comes the context block. This confuses me. Why should I use context block when I can have nested describe for different contexts?

Is there any advantage? Also is my assumption of describe as a context basically wrong?

Thanks for any help.

context and describe do exactly the same thing (they even run the same code: context is an alias of describe) the difference is the intent they express. Here’s how I usually use them:

  • describe indicates what I’m testing, I usually pass it a class or the name of a method.
  • context indicates some special set of circumstances that effect the test, I usually only use for a method that has several clearly separate outcomes each of which would need multiple it blocks to describe.

Here’s an example of the structure of some specs for the import method on an Importer object:

describe Importer do
  describe '#import' do
    context 'with an empty source file' do
      # …
    end

    context 'with an invalid source file' do
      # …
    end
  end
end

I could have used describe everywhere, but I think the distinction makes the code more clear: I am describing the Importer#import method, and in a particular context I expect it to …

Hope that helps.

1 Like

thanks @georgebrock for taking time to point me to the exact source code where the alias is defined.