78

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
2
  • 1
    Note that an object is never an "instance of another object." An object is an instance of a class, not another object. Commented Jul 15, 2020 at 0:09
  • 1
    @JacobLockard Classes are objects in Ruby. The Ruby documentation states: "Classes in Ruby are first-class objects—each is an instance of class Class." and "When a new class is created, an object of type Class is initialized and assigned to a global constant." ruby-doc.org/core-2.5.3/Class.html Commented Jul 23, 2020 at 22:47

2 Answers 2

165

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:

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.should be_an_instance_of Shirt
@object.should be_an_instance_of Garment
Sign up to request clarification or add additional context in comments.

Comments

8

You mean you want to check if an object is an instance of a class? If so, that's easy, just use class:

@object.class.should == Shirt

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.