user1568617
user1568617

Reputation: 81

Contexts in rspec

I have a basic doubt. If the rspec file contains many contexts:

describe Name do
context "number1" do
.......
.......
end
context "number 2" do
.......
.......
end
context "number 3" do
.......
.......
end

How should the functions from each of the contexts be described in the .rb file? Should they be in the same class or different class? Is there any book I can read to improve my knowledge about this?

Upvotes: 1

Views: 6151

Answers (1)

MrDanA
MrDanA

Reputation: 11647

The structure I use when defining rspec files (based on reading I've done on rspec) is that you use describes to describe specific functions, and context to talk about a specific context of state and/or path through the function.

Example class:

class MyClass
    def self.my_class_method(bool)
        if bool == true
            return "Yes"
        else
            return "No"
        end
    end

    def my_instance_method
        today = Date.today
        if today.month == 2 and today.day == 14
            puts "Valentine's Day"
        else
            puts "Other"
        end
     end
end

As you can see, I've defined a class method and an instance method that do really silly and random functions. But the point is this: the class method will do something different based on the argument, and the instance method will do something different based on some outside factor: you need to test all these, and these are different contexts. But we will describe the functions in the rspec file.

Rspec file:

describe MyClass do
    describe ".my_class_method" do
        context "with a 'true' argument" do
            it "returns 'Yes'." do
                MyClass.my_class_method(true).should eq "Yes"
            end
        end

        context "with a 'false' argument" do
            it "returns 'No'." do
                MyClass.my_class_method(false).should eq "No"
            end
        end
    end

    describe "#my_instance_method" do
        context "on Feb 14" do
            it "returns 'Valentine's Day'." do
                Date.stub(:today) { Date.new(2012,2,14) }
                MyClass.new.my_instance_method.should eq "Valentine's Day"
            end
        end

        context "on a day that isn't Feb 14" do
            it "returns 'Other'." do
                Date.stub(:today) { Date.new(2012,2,15) }
                MyClass.new.my_instance_method.should eq "Other"
            end
        end
    end
end

So you can see the describe is for saying what method you're describing, and matches up with the name of a method in your class. The context is used to evaluate different conditions the method can be called in, or different states that affect the way the method works.

Hope this helps!

Upvotes: 11

Related Questions