本文介绍了如何使用rspec检查变量是否是模块子类的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的类结构:

I have a class structure that looks like this:

module MyModule

    class MyOuterClass

        class MyInnerClass

        end

    end

end

我试图确保使用Rspec将变量正确实例化为MyInnerClass.打印类的类型是MyModule :: MyOuterClass :: MyInnerClass.但是,如果我尝试运行该行

I'm trying to make sure that a variable was correctly instantiated as a MyInnerClass using Rspec. printing the type of the class, it was MyModule::MyOuterClass::MyInnerClass. However, if I try to run the line

expect{@instance_of_MyInnerClass}.to be_an_instance_of(MyModule::MyOuterClass::MyInnerClass)

我收到错误消息您必须传递参数而不是块才能使用提供的匹配器."另外,这些课程在另一个位置,所以我不能只检查

I get the error "You must pass an argument rather than a block to use the provided matcher." Additionally, the classes are in another location, so I can't just check

[...] be_an_instance_of(MyInnerClass)

Rspec抱怨MyInnerClass是一个未初始化的常量.因此,我想问一下如何使用RSpec验证变量是MyInnerClass的实例.

Rspec complains that MyInnerClass is an uninitialized constant. So, I would like to ask how to verify that a variable is an instance of MyInnerClass using RSpec.

推荐答案

不要越过障碍

Rspec 3.x使用预期的方法而不是块语法(请参阅 RSpec 3期望3.0 ).要使您的规范通过并清理,可以使用以下命令:

Don't Pass a Block

Rspec 3.x uses an expect method rather than a block syntax (see RSpec 3 Expectations 3.0). To get your spec to pass, and clean it up, you can use the following:

module MyModule
  class MyOuterClass
    class MyInnerClass
    end
  end
end

describe MyModule::MyOuterClass::MyInnerClass do
  it "is correctly instantiated" do
    expect(subject).to be_an_instance_of MyModule::MyOuterClass::MyInnerClass
  end
end

请注意隐式主题的使用,该主题作为参数传递给#expect.当然可以改为传递其他局部变量或实例变量,但是在这种情况下, subject 已经为您定义为MyModule::MyOuterClass::MyInnerClass.new.

Note the use of the implicit subject, passed as an argument to #expect. You can certainly pass other local or instance variables instead, but in this case subject is already defined for you as MyModule::MyOuterClass::MyInnerClass.new.

这篇关于如何使用rspec检查变量是否是模块子类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 14:16