2016-09-18 88 views
0

我正在努力学习RSpec。目前我正在研究built-in matchersRSpec kind_of?返回错误结果

我对expect(actual).to be_kind_of(expected)

relishapp site有点糊涂了,它说的be_kind_of行为是

obj.should be_kind_of(类型):调用obj.kind_of(型),其中如果type在obj的类层次结构中或者是一个模块并且包含在obj类层次结构中的类中,则返回true。

APIdock状态this example

module M; end 
class A 
    include M 
end 
class B < A; end 
class C < B; end 

b.kind_of? A  #=> true 
b.kind_of? B  #=> true 
b.kind_of? C  #=> false 
b.kind_of? M  #=> true 

然而,当我测试RSpec的,则返回false当我这样做:

module M; end 
class A 
    include M 
end 
class B < A; end 
class C < B; end 

describe "RSpec expectation" do 
    context "comparisons" do 
    let(:b) {B.new} 

    it "test types/classes/response" do 
     expect(b).to be kind_of?(A) 
     expect(b).to_not be_instance_of(A) 
    end 
    end 
end 


1) RSpec expectation comparisons test types/classes/response 
    Failure/Error: expect(b).to be kind_of?(A) 

     expected false 
      got #<B:70361555406320> => #<B:0x007ffca7081be0> 

为什么我的RSpec返回false当例子说它应该返回true

回答

0

你混合了两种匹配器should and expect。检查文档rspec-expectations

expect(actual).to be_an_instance_of(expected) # passes if actual.class == expected 
expect(actual).to be_a(expected)    # passes if actual.kind_of?(expected) 
expect(actual).to be_an(expected)    # an alias for be_a 
expect(actual).to be_a_kind_of(expected)  # another alias 

你应该选择use both,或其中之一。

1

你写了

expect(b).to be kind_of?(A) 

,但在匹配是

expect(b).to be_kind_of(A) 

注意下划线和缺乏一个问号。 如果

b.equal?(kind_of?(A)) 

你对Rspec的测试本身调用#kind_of?没有b,你将与匹配你写的测试将通过。