Shrikant Khadilkar
Shrikant Khadilkar

Reputation: 350

Why does this RSpec example behave such

Just trying out some RSpec expectations and wondering why this happens

describe "rspec" do
    class Team
        def players_on
        11
        end
    end

    it "does wierd things" do           
        hometeam1 = Team.new
        hometeam1.should have(11).players_on         
    end
end

RSpec shows an error

 Failure/Error: hometeam1.should have(11).players_on
       expected 11 players_on, got 8

If I substitute 11 with 8 in the expectation it passes

Is something wrong with my computer ???

Upvotes: 0

Views: 41

Answers (2)

Shrikant Khadilkar
Shrikant Khadilkar

Reputation: 350

this is what i should have done....

describe "rspec" do
    class Team

        def initialize
            @x = ["tom","dick","harry"]
        end

        def players_on_field
            @x      
        end
    end

    it "does wierd things" do           
        hometeam1 = Team.new
        hometeam1.should have(3).players_on_field        
    end
end

Upvotes: 0

Andrew Marshall
Andrew Marshall

Reputation: 96934

You’re using the have matcher incorrectly. From the docs:

RSpec provides several matchers that make it easy to set expectations about the size of a collection…These work on any collection-like object—the object just needs to respond to #size or #length (or both).

Which means that it calls size/length on the object, so your expectation is the same as:

hometeam1.players_on.size.should == 11

and 11.size is 8 (so 8.should == 11, which is of course false). You should use a regular matcher instead:

hometeam1.players_on.should == 11

Upvotes: 3

Related Questions