61

我需要一种方法来检查一个对象是否是使用 RSpec 的另一个对象的实例。例如:

describe "new shirt" do
  it "should be an instance of a Shirt object"
    # How can i check if it is an instance of a shirt object
  end
end
4

2 回答 2

140

首选语法是:

expect(@object).to be_a Shirt

较旧的语法是:

@object.should be_an_instance_of Shirt

请注意,两者之间存在非常细微的差异。如果 Shirt 从 Garment 继承,那么这两个期望都会过去

expect(@object).to be_a Shirt
expect(@object).to be_a Garment

如果你这样做并且@object 是衬衫,那么第二个期望将失败

@object.should be_an_instance_of Shirt
@object.should be_an_instance_of Garment
于 2012-12-20T04:19:52.530 回答
7

你的意思是你想检查一个对象是否是一个的实例?如果是这样,那很容易,只需使用class

@object.class.should == Shirt
于 2012-11-25T04:59:16.927 回答