2016-09-18 62 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,你將與匹配你寫的測試將通過。