Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

describe vs context in rspec. Differences? [duplicate]

I've read a little bit about how one should organize rspec code. It seems like "context" is used more for states of objects. In your words, how would you describe how to use "describe" in rspec code?

Here is a snippet of my movie_spec.rb code:

require_relative 'movie'

describe Movie do

    before do
        @initial_rank = 10
        @movie = Movie.new("goonies", @initial_rank)
    end


    it "has a capitalied title" do
        expect(@movie.title) == "Goonies"
    end


    it "has a string representation" do
        expect(@movie.to_s).to eq("Goonies has a rank of 10")
    end

    it "decreases rank by 1 when given a thumbs down" do
        @movie.thumbs_down
        expect(@movie.rank).to eq(@initial_rank - 1)
    end

    it "increases rank by 1 when given a thumbs up" do
        @movie.thumbs_up
        expect(@movie.rank).to eq(@initial_rank + 1)
    end

    context "created with a default rank" do
        before do
            @movie = Movie.new("goonies")
        end

        it "has a rank of 0" do
            expect(@movie.rank).to eq(5)
        end
    end
like image 817
Jwan622 Avatar asked Oct 21 '14 01:10

Jwan622


People also ask

When to use describe and context?

There is not much difference between describe and context . The difference lies in readability. I tend to use context when I want to separate specs based on conditions. I use describe to separate methods being tested or behavior being tested.

What is describe context?

1 : the parts of a discourse that surround a word or passage and can throw light on its meaning. 2 : the interrelated conditions in which something exists or occurs : environment, setting the historical context of the war.

What is describe in RSpec?

The word describe is an RSpec keyword. It is used to define an “Example Group”. You can think of an “Example Group” as a collection of tests. The describe keyword can take a class name and/or string argument.

What is let in RSpec?

let generates a method whose return value is memoized after the first call. This is known as lazy loading because the value is not loaded into memory until the method is called. Here is an example of how let is used within an RSpec test. let will generate a method called thing which returns a new instance of Thing .


1 Answers

There is not much difference between describe and context. The difference lies in readability. I tend to use context when I want to separate specs based on conditions. I use describe to separate methods being tested or behavior being tested.

One main thing that changed in the latest RSpec is that "context" can no longer be used as a top-level method.

like image 124
Leo Correa Avatar answered Oct 17 '22 03:10

Leo Correa