ruby 使用 RSpec 检查某物是否是另一个对象的实例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13548375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using RSpec to check if something is an instance of another object
提问by Dillon Benson
I need a way to check if an object is an instance of another object using RSpec. For example:
我需要一种方法来检查一个对象是否是另一个使用 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
回答by Dillon Benson
The preferred syntax is:
首选语法是:
expect(@object).to be_a Shirt
The older syntax is:
较旧的语法是:
@object.should be_an_instance_of Shirt
Note that there is a very subtle difference between the two. If Shirt were to inherit from Garment then both of these expectations will pass:
请注意,两者之间存在非常细微的差异。如果 Shirt 从 Garment 继承,那么这两个期望都会通过:
expect(@object).to be_a Shirt
expect(@object).to be_a Garment
If you do and @object is a Shirt, then the second expectation will fail:
如果你这样做并且@object 是一件衬衫,那么第二个期望将失败:
@object.should be_an_instance_of Shirt
@object.should be_an_instance_of Garment
回答by Chris Salzberg
You mean you want to check if an object is an instance of a class? If so, that's easy, just use class:
你的意思是你想检查一个对象是否是一个类的实例?如果是这样,那很简单,只需使用class:
@object.class.should == Shirt

