RSpec 种类?返回错误结果

Igg*_*ggy 2 rspec ruby-on-rails

我正在寻求学习 RSpec。目前我正在研究内置匹配器

我有点困惑expect(actual).to be_kind_of(expected)

relishapp网站上,它说的行为be_kind_of

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

APIdock 给出了这个例子

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
Run Code Online (Sandbox Code Playgroud)

但是,当我在 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>
Run Code Online (Sandbox Code Playgroud)

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

小智 5

你正在写

expect(b).to be kind_of?(A)
Run Code Online (Sandbox Code Playgroud)

但匹配器是

expect(b).to be_kind_of(A)
Run Code Online (Sandbox Code Playgroud)

请注意下划线和缺少问号。如果满足以下条件,您编写的测试就会通过

b.equal?(kind_of?(A))
Run Code Online (Sandbox Code Playgroud)

您调用#kind_of?的是 Rspec 测试本身,而不是b调用匹配器。