Testing with RSpec — contexts

Testing with RSPEC

Hey, folks! One of our tasks is related with tests (of course!). We had to create and refactor tests for a lot of models and controllers created by us in the issues.
One of our mentor’s suggestions was to use context and that makes me wonder what is the context purpose. Then I search.

Generally, the models’ tests have both describe and context. So, why is that?
Apparently, the describe has a broad purpose and it is used to characterize a whole functionality test — with all scenarios. For example, I would like to test a new method of my model. I would do:

describe "my new method" do
// setup the subject
// here I put all the possible scenarios for my tests

However, inside the describe, it is really possible that you would like to test your subject with distinct states. This is when the context appears. Let’s see:

describe "my new method" do
// setup the subjects:
before(:each) do
@user = User.first
context “when my user is logged in” do
log_in @user
// test all the scenarios with user logged in
context “when the user is not logged in” do
// expect different results when user is not logged in

Basically, by using the context inside describe your tests become easier to read and more organized too. So, remember: describe a method with contexts for states.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade