Using RSpec to verify that something is an instance of another object

I need a way to check if an object is an instance of another object using RSpec. For example:

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 
+42
ruby instance testing rspec
Nov 25
source share
2 answers

Preferred syntax:

 expect(@object).to be_a Shirt 

Older syntax:

 @object.should be_an_instance_of Shirt 

Please 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 :

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

If you do this and @object is a Shirt, then the second wait will not be :

 @object.should be_an_instance_of Shirt @object.should be_an_instance_of Garment 
+99
Dec 20 '12 at 4:19
source share

Do you want to check if an object is an instance of a class? If so, simply use class :

 @object.class.should == Shirt 
+7
Nov 25
source share



All Articles