Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 为什么这个RSpec示例的行为如此_Ruby_Rspec - Fatal编程技术网

Ruby 为什么这个RSpec示例的行为如此

Ruby 为什么这个RSpec示例的行为如此,ruby,rspec,Ruby,Rspec,只是尝试一下RSpec的一些期望,想知道为什么会发生这种情况 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 e

只是尝试一下RSpec的一些期望,想知道为什么会发生这种情况

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显示一个错误

 Failure/Error: hometeam1.should have(11).players_on
       expected 11 players_on, got 8
如果我用8代替11,期望它通过


我的电脑有问题吗?

您使用的
匹配器不正确。发件人:

RSpec提供了几个匹配器,可以轻松设置对 集合的大小…这些作用于任何集合,如对象只需响应
\size
\length
(或两者兼而有之)的对象

这意味着它调用对象上的
size
/
length
,因此您的期望值与:

hometeam1.players_on.size.should == 11
11.size
8
(因此
8.should==11
,这当然是错误的)。您应该改用常规匹配器:

hometeam1.players_on.should == 11

您错误地使用了
have
匹配器。发件人:

RSpec提供了几个匹配器,可以轻松设置对 集合的大小…这些作用于任何集合,如对象只需响应
\size
\length
(或两者兼而有之)的对象

这意味着它调用对象上的
size
/
length
,因此您的期望值与:

hometeam1.players_on.size.should == 11
11.size
8
(因此
8.should==11
,这当然是错误的)。您应该改用常规匹配器:

hometeam1.players_on.should == 11

这是我应该做的

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

这是我应该做的

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