Reputation: 407
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
Reputation: 5039
expect(Blah.ref_class.class).to eq(Class)
expect(Blah.ref_class.ancestors).to include(SuperClass)
Use Amadan's answer. Here's an exerpt.
expect(Blah.ref_class).to eq(::Other::Thing)
expect(Blah.new).to be_an_instance_of(Blah)
expect(Blah.new).to be_an(Object) # or one of `be_a` `be_a_kind_of`
In Ruby, class of a class is Class.
class Sample
end
Sample.class #=> Class
Sample.class.ancestors #=> [Class, Module, Object, Kernel, BasicObject]
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]
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
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