RSpec kind_of?返回错误的结果

时间:2016-09-18 06:06:21

标签: ruby-on-rails rspec

我正在学习RSpec。目前我正在研究built-in matchers

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

感到有些困惑

relishapp site上,它表示be_kind_of的行为为

  

obj.should be_kind_of(type):调用obj.kind_of?(type),如果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在示例说它应该返回true时返回false?

2 个答案:

答案 0 :(得分:1)

你正在写

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

但是匹配器是

expect(b).to be_kind_of(A)

请注意下划线和缺少问号。 你写的测试将通过

b.equal?(kind_of?(A))

您在Rspec测试本身上调用#kind_of?而不是b,就像使用匹配器一样。

答案 1 :(得分: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或其中一个。