user3809888
user3809888

Reputation: 407

Checking that a class reference is returned with RSpec?

Say I've defined a Ruby class along these lines:

class Blah
  def self.ref_class
    ::Other::Thing
  end
end

.ref_class returns a class reference (that's what it's called, right?). How do I test this method with RSpec?

Upvotes: 3

Views: 2054

Answers (2)

Pooyan Khosravi
Pooyan Khosravi

Reputation: 5039

Examples

To ensure it is a Class

expect(Blah.ref_class.class).to eq(Class)

To ensure it extends another Class or includes other Modules

expect(Blah.ref_class.ancestors).to include(SuperClass)

To ensure it is a specific class

Use Amadan's answer. Here's an exerpt.

expect(Blah.ref_class).to eq(::Other::Thing)

To ensure it is an instance of a specific class

expect(Blah.new).to be_an_instance_of(Blah)

To ensure it is an instance of a specific class or one of its subclasses

expect(Blah.new).to be_an(Object) # or one of `be_a` `be_a_kind_of`

Background

Class

In Ruby, class of a class is Class.

class Sample
end

Sample.class #=> Class
Sample.class.ancestors #=> [Class, Module, Object, Kernel, BasicObject]

Ancestors

In Ruby, extended Classes and included or prepended Modules are part of ancestors list.

module IncludedModule
end

module PrependedModule
end

class Sample
  include IncludedModule
  prepend PrependedModule
end

Sample.ancestors #=> [PrependedModule, Sample, IncludedModule, Object, Kernel, BasicObject]

Instance

In Ruby, class of an instance is the class.

Sample.new.class #=> Sample

To check if an instance is exactly of specified class.

Sample.new.class == Sample #=> true # what be_an_instance_of checks.
Sample.new.instance_of? Sample #=> true
Sample.new.class == IncludedModule #=> false
Sample.new.instance_of? IncludedModule #=> false

To check if an instance's class is exactly specified class or one of its subclasses.

Sample.new.kind_of? IncludedModule #=> true # Same as #is_a?
Sample.new.class.ancestors.include? IncludedModule #=> true

Upvotes: 6

Amadan
Amadan

Reputation: 198324

It's just a normal return value, like "hello"; but of class Class. So just check that the function returns the value it is supposed to. Where you'd expect(Greeting.in_morning).to eq "hello", in this case, expect(Blah.ref_class).to eq ::Other::Thing.

Upvotes: 1

Related Questions