【发布时间】:2016-03-29 03:03:12
【问题描述】:
假设我已经按照这些思路定义了一个 Ruby 类:
class Blah
def self.ref_class
::Other::Thing
end
end
.ref_class 返回一个类引用(这就是它的名称,对吧?)。如何使用 RSpec 测试此方法?
【问题讨论】:
标签: ruby-on-rails ruby rspec rspec-rails
假设我已经按照这些思路定义了一个 Ruby 类:
class Blah
def self.ref_class
::Other::Thing
end
end
.ref_class 返回一个类引用(这就是它的名称,对吧?)。如何使用 RSpec 测试此方法?
【问题讨论】:
标签: ruby-on-rails ruby rspec rspec-rails
expect(Blah.ref_class.class).to eq(Class)
expect(Blah.ref_class.ancestors).to include(SuperClass)
使用 Amadan 的答案。这是一段摘录。
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`
在 Ruby 中,类的类是 Class。
class Sample
end
Sample.class #=> Class
Sample.class.ancestors #=> [Class, Module, Object, Kernel, BasicObject]
在 Ruby 中,扩展类和包含或附加的模块是祖先列表的一部分。
module IncludedModule
end
module PrependedModule
end
class Sample
include IncludedModule
prepend PrependedModule
end
Sample.ancestors #=> [PrependedModule, Sample, IncludedModule, Object, Kernel, BasicObject]
在 Ruby 中,实例的类就是类。
Sample.new.class #=> Sample
检查一个实例是否完全属于指定的类。
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
检查一个实例的类是否完全是指定的类或其子类之一。
Sample.new.kind_of? IncludedModule #=> true # Same as #is_a?
Sample.new.class.ancestors.include? IncludedModule #=> true
【讨论】:
只是一个普通的返回值,比如"hello";但属于Class。所以只需检查函数是否返回它应该返回的值。你在哪里expect(Greeting.in_morning).to eq "hello",在这种情况下,expect(Blah.ref_class).to eq ::Other::Thing。
【讨论】: