【问题标题】:Checking that a class reference is returned with RSpec?检查是否使用 RSpec 返回了类引用?
【发布时间】: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


    【解决方案1】:

    示例

    确保它是一个类

    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
    

    【讨论】:

      【解决方案2】:

      只是一个普通的返回值,比如"hello";但属于Class。所以只需检查函数是否返回它应该返回的值。你在哪里expect(Greeting.in_morning).to eq "hello",在这种情况下,expect(Blah.ref_class).to eq ::Other::Thing

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-07-28
        • 1970-01-01
        • 2011-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-25
        相关资源
        最近更新 更多